【问题标题】:Parsing JSON into a Map将 JSON 解析为 Map
【发布时间】:2019-09-29 04:13:23
【问题描述】:

我正在尝试将以下 JSON 字符串解析为键值对,以便将其插入数据库中的表中。

{
    "name": "MyMobile",
    "category": "cellphone",
    "details": {
        "displayAspectRatio": "97:3",
        "audioConnector": "none",
        "motherBoard": {
            "Rom": "256GB",
            "Ram": "8GB",
            "Battery": "400mAH"
        }
    }
}

我可以使用以下代码和GSON 解析 JSON 字符串并将其存储到 Map 中。但不幸的是,它不适用于嵌套的 JSON 对象。

public static HashMap<String, Object> createHashMapFromJsonString(String json) {

JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
HashMap<String, Object> map = new HashMap<String, Object>();

while (iterator.hasNext()) {

    Map.Entry<String, JsonElement> entry = iterator.next();
    String key = entry.getKey();
    JsonElement value = entry.getValue();

    if (null != value) {
        if (!value.isJsonPrimitive()) {
            if (value.isJsonObject()) {

                map.put(key, createHashMapFromJsonString(value.toString()));
            } else if (value.isJsonArray() && value.toString().contains(":")) {

                List<HashMap<String, Object>> list = new ArrayList<>();
                JsonArray array = value.getAsJsonArray();
                if (null != array) {
                    for (JsonElement element : array) {
                        list.add(createHashMapFromJsonString(element.toString()));
                    }
                    map.put(key, list);
                }
            } else if (value.isJsonArray() && !value.toString().contains(":")) {
                map.put(key, value.getAsJsonArray());
            }
        } else {
            map.put(key, value.getAsString());
           }
       }
   }
   return map;
  }
}

我希望我的地图中有以下行。谁能指导我正确的方法?

name = MyMobile
category = cellphone
details.displayAspectRatio = 97:3
details.audioConnector = none
details.motherBoard.Rom = 256GB
details.motherBoard.Ram = 8GB
details.motherBoard.Battery = 400mAH

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    对于嵌套的 JSON,上述问题可以通过递归来解决。请参见下面的代码。注意:仅处理 Map、//TODO ArrayList 和异常处理

    @Test
    public void testJsonToMap() {
        String data = "{\"name\":\"MyMobile\",\"category\":\"cellphone\",\"details\":{\"displayAspectRatio\":\"97:3\",\"audioConnector\":\"none\",\"motherBoard\":{\"Rom\":\"256GB\",\"Ram\":\"8GB\",\"Battery\":\"400mAH\"}}}";
        Gson gson = new GsonBuilder().create();
        Map jsonMap = gson.fromJson(data, Map.class);
        System.out.println(jsonMap);
    
        Sep2019JavaTest test = new Sep2019JavaTest();
        Map opMap = test.toMap(jsonMap, new HashMap<String, Object>(), "");
        System.out.println(opMap);
    }
    
    private Map toMap(Map ipMap, Map opMap, String parentKey) {
        if (ipMap != null && !ipMap.isEmpty()) {
            ipMap.forEach((k, v) -> {
                String key = parentKey.isEmpty() ? k.toString() : parentKey.concat(".").concat(k.toString());
                if (v.getClass() == LinkedTreeMap.class) {
                    toMap((Map) v, opMap, key);
                } else {
                    opMap.put(key, v);
                }
    
            });
        }
        return opMap;
    }
    
    //Output
    //{details.motherBoard.Rom=256GB, details.motherBoard.Battery=400mAH, name=MyMobile, category=cellphone, details.audioConnector=none, details.motherBoard.Ram=8GB, details.displayAspectRatio=97:3}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2020-02-14
      • 2020-05-20
      相关资源
      最近更新 更多