有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

示例Json:

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

java程序:这里假设map正在填充json文件。现在,当我运行下面的程序时,它在第^{行抛出错误

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());

错误: enter image description here

在这里,我想通过流api处理后,它应该会得到结果

List of [Test1, Test2, Test3]

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


共 (2) 个答案

  1. # 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]
    
  2. # 2 楼答案

    你能试试吗

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