将 JSON 解析为 Map

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


{

    "name": "MyMobile",

    "category": "cellphone",

    "details": {

        "displayAspectRatio": "97:3",

        "audioConnector": "none",

        "motherBoard": {

            "Rom": "256GB",

            "Ram": "8GB",

            "Battery": "400mAH"

        }

    }

}

我可以使用以下代码解析 JSON 字符串GSON并将其存储到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


呼啦一阵风
浏览 66回答 1
1回答

12345678_0001

对于嵌套的 JSON,上述问题可以通过递归来解决。请参阅下面的代码。注意:仅处理 Map、//TODO ArrayList 和异常处理@Testpublic void testJsonToMap() {&nbsp; &nbsp; String data = "{\"name\":\"MyMobile\",\"category\":\"cellphone\",\"details\":{\"displayAspectRatio\":\"97:3\",\"audioConnector\":\"none\",\"motherBoard\":{\"Rom\":\"256GB\",\"Ram\":\"8GB\",\"Battery\":\"400mAH\"}}}";&nbsp; &nbsp; Gson gson = new GsonBuilder().create();&nbsp; &nbsp; Map jsonMap = gson.fromJson(data, Map.class);&nbsp; &nbsp; System.out.println(jsonMap);&nbsp; &nbsp; Sep2019JavaTest test = new Sep2019JavaTest();&nbsp; &nbsp; Map opMap = test.toMap(jsonMap, new HashMap<String, Object>(), "");&nbsp; &nbsp; System.out.println(opMap);}private Map toMap(Map ipMap, Map opMap, String parentKey) {&nbsp; &nbsp; if (ipMap != null && !ipMap.isEmpty()) {&nbsp; &nbsp; &nbsp; &nbsp; ipMap.forEach((k, v) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String key = parentKey.isEmpty() ? k.toString() : parentKey.concat(".").concat(k.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (v.getClass() == LinkedTreeMap.class) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toMap((Map) v, opMap, key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; opMap.put(key, v);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; 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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java