如何解决如何解析json包括java对象中的map和arraylist
我正在使用 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,List<String>>>) objectMapper.readValue(sampleJson,new TypeReference<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());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。