如何解析 json 在 java 对象中包含 map 和 arraylist

How to parse json include map and arraylist in java object

我正在使用 java8 流 api 并想解析一个 Json 文件,然后使用流 api 获得所需的输出。

样本Json:

{
  "map1":{
    "Test1":
    [
      "1"
    ],
    "Test2":
    [
      "2",
      "3"
    ]
  },
  "map2":{
    "Test3":[
      "4",
      "5"
    ]
  }
}

java 程序:这里假设地图正在填充 json 文件非常好。现在,当我是 运行 以下程序时,它会在 .flatMap(e -> Stream.of(((Map.Entry)e).getKey())) ).

行抛出错误
Map map = objectMapper.readValue("test", Map.class);

ArrayList response = (ArrayList) map.entrySet().stream()
        .flatMap(e -> Stream.of(((Map.Entry)e).getValue()))
        .flatMap(e -> Stream.of(((Map)e).keySet()))
        .flatMap(e -> Stream.of(((Map.Entry)e).getKey()))
        .collect(Collectors.toList());

错误:

在这里,我希望通过流 api 处理后应该得到结果。

List of [Test1, Test2, Test3]

有人可以看看这段代码吗?如果它不能正常工作,可以提出其他建议。

您可以使用对象映射器的 readValue() 方法使用 TypeReference 创建一个 Map<String, Map<String, List<String>>>,然后提取所需的结果:

Collection<String> response = ((Map<String, Map<String, List<String>>>) objectMapper.readValue(sampleJson,
        new TypeReference<Map<String, Map<String, List<String>>>>() {})) 
        .values() // to get a collection of Map<String, List<String>>
        .stream().map(m -> m.keySet()) // to get the key set of the map which has the values we want
        .flatMap(Set::stream) // to flatten the collection of sets 
        .collect(Collectors.toList()); // to collect each value to a list

输出:

[Test1, Test2, Test3]

你能试试吗?

ArrayList response = (ArrayList) map.values()
                                            .stream()
                                            .map(it -> ((Map)it).keySet())
                                            .flatMap(it -> ((Set<?>) it).stream())
                                            .collect(Collectors.toList());