如何使用杰克逊将 json 转换为列表/地图

我遇到了一段json如下:

{
  "code": 1,
  "msg": "query success",
  "obj": {
    "data": [
      {
        "name": "",
        "value": {
          "num": "89"
        }
      },
      {
        "name": "1",
        "value": {
          "num": "19"
        }
      },
      {
        "name": "2",
        "value": {
          "num": "6"
        }
      }
    ]
  },
  "success": true,
  "duration": 523
}

我需要 namenum 。如何使用 Jackson 将其转换为 java.util.List<HashMap<String, String>> 列表?

stack overflow how to convert json to list/map with jackson
原文答案
author avatar

接受的答案

您可以将 Jackson ObjectMapperTypeReference 一起使用,首先您需要将其读取为 Map<String,Object> 然后您可以使用 Java 提取名称和编号。

您需要从 data 获取 obj 然后对于 dataList 中的每个项目,您必须将其映射到新的 HashMap ,如下所示

ObjectMapper objectMapper = new ObjectMapper ();
Map<String,Object> jsonMap = objectMapper.readValue(jsonData,new TypeReference<Map<String,Object>>(){});
List<Object> data = ((Map<String,Object>)jsonMap.get("obj")).get("data");
List<Map<String,String> result = data.stream()
   .map(d->(Map<String,Object> d)
   .map(d->{
      Map<String,String> map = new HashMap();
      map.put(d.get("name"),((Map<String,String>)d.get("value")).get("num"));
      return map;
      })
   .collect(Collectors.toList());

但是,如果您可以为数据创建一个 class ,它会更容易一些。


答案:

作者头像

Josson 可以完成这项工作。

https://github.com/octomix/josson

反序列化

Josson josson = Josson.fromJsonString(
    "{" +
    "  "code": 1," +
    "  "msg": "query success"," +
    "  "obj": {" +
    "    "data": [" +
    "      {" +
    "        "name": ""," +
    "        "value": {" +
    "          "num": "89"" +
    "        }" +
    "      }," +
    "      {" +
    "        "name": "1"," +
    "        "value": {" +
    "          "num": "19"" +
    "        }" +
    "      }," +
    "      {" +
    "        "name": "2"," +
    "        "value": {" +
    "          "num": "6"" +
    "        }" +
    "      }" +
    "    ]" +
    "  }," +
    "  "success": true," +
    "  "duration": 523" +
    "}");

转型

JsonNode node = josson.getNode("obj.data.map(name::value.num)");
System.out.println(node);

List<Map<String, String>> result = Josson.readValueFor(node, List.class);
System.out.println(result);

输出

[{"":"89"},{"1":"19"},{"2":"6"}]

[{=89}, {1=19}, {2=6}]