码迷,mamicode.com
首页 > Web开发 > 详细

json字符串转换为多级Map -list-map的形式

时间:2015-07-30 19:28:53      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:josn   map   

网上找了好多方法都是一级的,由于需要多级map,于是做如下封装


public static Map<String, Object> parseJSON2Map(String jsonStr){  

        //最外层解析  
        if(jsonStr!=null&&jsonStr.startsWith("{")&&jsonStr.endsWith("}")){
            Map<String, Object> map = new HashMap<String, Object>();  
            
            JSONObject json = JSONObject.fromObject(jsonStr);  
            for(Object k : json.keySet()){
                
                Object v = json.get(k);   
                //如果内层还是数组的话,继续解析  
                if(v instanceof JSONArray){  
                    List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();  
                    Iterator<JSONObject> it = ((JSONArray)v).iterator();  
                    while(it.hasNext()){  
                        JSONObject json2 = it.next();  
                        list.add(parseJSON2Map(json2.toString()));  
                    }  
                    map.put(k.toString(), list);  
                } else {  
                    Map<String, Object> m = parseJSON2Map(v.toString());
                    if(m==null)
                        map.put(k.toString(), v);
                    else
                        map.put(k.toString(), m);  
                }  
            }  
            return map;  
        }else{
            return null;
        }
    } 

版权声明:本文为博主原创文章,未经博主允许不得转载。

json字符串转换为多级Map -list-map的形式

标签:josn   map   

原文地址:http://blog.csdn.net/haiking5253/article/details/47154389

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!