zoukankan      html  css  js  c++  java
  • JSON字符串与Map互转

    //一、map转为json字符串

        public static String map2jsonstr(Map<String,?> map){
            return JSONObject.toJSONString(map);
        }

    //二、json字符串转Map对象

        public static Map<String,?> jsonstr2map(String jsonstr){
            return JSONObject.parseObject(jsonstr);
        }

    //三、json字符串转Map对象

    public static Map<String, Object> parseJSON2Map(String jsonStr){ 
    Map<String, Object> map = new HashMap<String, Object>(); 
    JSONObject json = JSONObject.parseObject(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<Object> it = ((JSONArray)v).iterator(); 
    while(it.hasNext()){ 
    JSONObject json2 = (JSONObject)it.next(); 
    list.add(parseJSON2Map(json2.toString())); 
    } 
    map.put(k.toString(), list); 
    } else { 
    map.put(k.toString(), v); 
    }

    return map; 
    }

    测试:

        public static void main(String[] args) {
        
            try {
                
                List list = new ArrayList();
                Map<String,Object> map = new HashMap<String,Object>();
                list.add(1);
                list.add("b");
                map.put("name", "a");
                map.put("age", 12);
                map.put("name", "a");
                map.put("list", list);
                String jsonstr = map2jsonstr(map);
                System.out.println("json字符串:" + jsonstr);
                System.out.println("map对象"+jsonstr2map(jsonstr));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }



  • 相关阅读:
    字符串Hash 学习笔记
    P4315 月下“毛景树” 题解
    page
    Equation
    Graph
    配置UOJ数据的正确姿势
    luogu2261余数求和题解--整除分块
    luogu2858奶牛零食题解--区间DP
    luogu1005矩阵取数游戏题解--区间DP
    luogu4677山区建小学题解--区间DP
  • 原文地址:https://www.cnblogs.com/xyzq/p/10266488.html
Copyright © 2011-2022 走看看