用java、hutool的JSONUtiltoList把 name John age 30 name Jane age 25 name John age 30
可以使用以下代码实现:
import cn.hutool.json.JSONUtil;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
String json = "[\n" +
" [\n" +
" {\n" +
" \"name\": \"John\",\n" +
" \"age\": 30\n" +
" },\n" +
" {\n" +
" \"name\": \"Jane\",\n" +
" \"age\": 25\n" +
" }\n" +
" ],\n" +
" [\n" +
" {\n" +
" \"name\": \"John\",\n" +
" \"age\": 30\n" +
" },\n" +
" {\n" +
" \"name\": \"Jane\",\n" +
" \"age\": 25\n" +
" }\n" +
" ]\n" +
"]";
List<List<Map<String, Object>>> list = JSONUtil.toList(JSONUtil.parseArray(json), List.class);
List<Map<String, Object>> result = list.stream().flatMap(l -> l.stream()).toList();
System.out.println(result);
}
}
输出结果为:
[{name=John, age=30}, {name=Jane, age=25}, {name=John, age=30}, {name=Jane, age=25}]
首先使用JSONUtil.parseArray将json字符串解析成JSONArray,然后再使用JSONUtil.toList将JSONArray转化成List<List<Map<String, Object>>>。最后使用stream流将嵌套的List展开,转化成List<Map<String, Object>>。
原文地址: https://www.cveoy.top/t/topic/bsiU 著作权归作者所有。请勿转载和采集!