【问题标题】:How to parse json include map and arraylist in java object如何在java对象中解析json包括map和arraylist
【发布时间】:2021-03-26 12:30:35
【问题描述】:

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

Json 示例:

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

java 程序:这里假设 map 可以完美地填充 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]

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

【问题讨论】:

  • map.values().stream().flatMap(m -> ((Map) m).keySet().stream()).collect(Collectors.toList()); 呢?
  • 如果我想像 1,2,3,4,5 这样的平面值怎么办

标签: java json jackson java-stream objectmapper


【解决方案1】:

您可以使用对象映射器的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]

【讨论】:

  • 如果我想像 1,2,3,4,5 这样的平面值怎么办
  • 那么你应该得到m.values() 而不是m.keySet() : .values().stream().flatMap(m -&gt; m.values().stream()).flatMap(Collection::stream) .collect(Collectors.toList());
【解决方案2】:

你可以试试吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多