我有这个输出 JSON。它来自这个类型的List<List<TextValue>>
TextValue 类是String 文本,String 值。
"data": [
[
{
"text": "DescCode",
"value": "01"
},
{
"text": "DescName",
"value": "Description 1"
},
{
"text": "SecondCode",
"value": "01"
}
],
[
{
"text": "DescCode",
"value": "02"
},
{
"text": "DescName",
"value": "Description 2"
},
{
"text": "SecondCode",
"value": "02"
}
]
]
我想将它转换为这个 JSON。我相信这将是这个对象设置。List<Map<String, String>>
"data": [
{
"DescCode": "01",
"DescName": "Description 1",
"SecondCode": "01"
},
{
"DescCode":"02",
"DescName":"Description 2",
"SecondCode":"02"
}
]
我的 JSON 是由我的 Spring REST 控制器自动创建的,所以我真的只需要 Java 对象,Json 仅用于参考。我对这个有偏见吗?List<Map<String, String>>
这是嵌套的TextValue
对象列表。
List<List<TextValue>> list = List.of(
List.of(new TextValue("DescCode", "01"),
new TextValue("DescName", "Description 1"),
new TextValue("SecondCode", "01")),
List.of(new TextValue("DescCode", "02"),
new TextValue("DescName", "Description 2"),
new TextValue("SecondCode", "02")));
这基本上流式传输内部列表,然后流式传输每个列表以创建具有指定键和值的映射。然后将这些地图收集到一个列表中。
List<Map<String,String>> listOfMaps = list.stream()
.map(lst->lst.stream()
.collect(Collectors.toMap(TextValue::getText, TextValue::getValue)))
.collect(Collectors.toList());
listOfMaps.forEach(System.out::println);
印刷
{DescName=Description 1, DescCode=01, SecondCode=01}
{DescName=Description 2, DescCode=02, SecondCode=02}
TextValue 类。
class TextValue {
String text;
String value;
public TextValue(String text, String value) {
this.text = text;
this.value = value;
}
public String getText() {
return text;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.format("%s, %s", text, value);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句