如何用Jackson实现json到list/map转换

6ioyuze2  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(148)

我遇到的一段简文如下图:

{
  "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〉〉的列表?

bvhaajcl

bvhaajcl1#

你可以用TypeReference来使用JacksonObjectMapper,首先你需要把它读成Map〈String,Object〉,然后你可以用Java来提取name和num。
您需要从obj中获取data,然后对于dataList中的每个项目,您必须将其Map到新的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,则会更容易一些。

9rygscc1

9rygscc12#

库 * 乔森 * 可以胜任这项工作。
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}]

相关问题