【问题标题】:Plain Json String to HashMap纯 Json 字符串到 HashMap
【发布时间】:2014-10-10 04:50:02
【问题描述】:

有很多问题需要转换json to HashMap。 希望对大家有帮助。

以下代码会将直接值或值的Array 转换为HashMap

【问题讨论】:

    标签: java json hashmap


    【解决方案1】:

    //递归调用函数

     private static Map getMap(JSONObject object, String json) throws Exception {
            Map<String, Object> map = new HashMap<String, Object>();
            Object jsonObject = null;
    
            Iterator<String> keys = object.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                Object value = object.get(key);
    
                if (value instanceof JSONObject) {
                    map.put(key, getMap((JSONObject) value, json));
                    continue;
                }
    
             // If value is in the form of array
    
                if (value instanceof JSONArray) {
                    JSONArray array = ((JSONArray) value);
                    List list = new ArrayList();
                    for (int i = 0 ; i < array.length() ; i++) {
                        jsonObject = array.get(i);
                        if (jsonObject instanceof JSONObject) {
                            list.add(getMap((JSONObject) jsonObject, json));
                        } else {
                            list.add(jsonObject);
    
                        }
                    }
                    map.put(key, list);
                    continue;
                }
    
                map.put(key, value);
            }
            return map;
        }
    

    //调用方法

    public static Map<String, Object> convertJsonToMap(String json) {
            Map<String, Object> map = new HashMap<String, Object>();
            JSONObject jsonObject = null;
    
            try {
                if (null != json) {
                    jsonObject = new JSONObject(json);
                    map = getMap(jsonObject, json);
                }
    
            } catch (Exception e) {
                throw new SystemException("Unable to read JSOn Object");
                // TODO : Handle Exception
            }
            return map;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-23
      • 2014-03-27
      • 2013-01-28
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多