如何在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());
在这里,我想通过流api处理后,它应该会得到结果
List of [Test1, Test2, Test3]
如果这段代码不能正常工作,是否有人可以看到它或提出其他建议
# 1 楼答案
您可以使用对象映射器的
readValue()
方法使用TypeReference
创建Map<String, Map<String, List<String>>>
,然后提取所需的结果:输出:
# 2 楼答案
你能试试吗