我有以下对象列表
[ ObjectVO ( id = 151401 , code = 370 AAA , Origin id = 8628823 , state = SP , local = N , number = 998035 ) N , number=998039), ObjectVO(id=151401, code=370 AAA, Origin ID=8628853, state=SP, local=N , number=998041), ObjectVO(id=151402, code=371 AAA, Origin ID=8 state=SP, local=N, number=998035), ObjectVO(id=151402, code=371 MCC, Origin id=8628833, state=SP, local=N, number=998039), ObjectVO(id=151402, code=371). AAA, Origin ID=8628853, state=SP, local=N, number=998041),
ObjectVO ( id = 155852 , code = 0389 AAA , Origin id = 8627130 , state = SP , local = N , number = 996509 ) , number=996509)]
[
{
"id":151401,
"observation":"370 AAA",
"input":[
{
"id":0,
"state":"string"
"local":"string"
"number":0
},
{
"id":8628833,
"state":"SP"
"local":"N",
"number":9
} }
]
} }
]
创建如下代码:
MultiValueMap<String, Map<String,Object>> originalMap = new LinkedMultiValueMap<>();
for(Entry<Object, List<VoqueryBatch>> entry :
map1.entrySet()) {
originalMap . add ( entry . getKey ( ) . toString ( ) , Map . of (
"id", entry.getValue().iterator().next().getId,
"code", entry.getValue().iterator().next().getCode(),
"idOrigin", entry.getValue().iterator().next().getIdOrigin(),
"state", entry.getValue().iterator().next().getState(),
"local", entry.getValue().iterator().next().getLocal(),
"number", entry.getValue().iterator().next().getNumber()
));
} }
List<ObjectNode> newList = new ArrayList<>();
for ( String entry : originalMap . keySet ()) {
List<Map<String, Object>> list = originalMap.get(entry);
ObjectNode objNode = new ObjectMapper().createObjectNode();
objNode.put("id", (Long)lotList.get(0).get("id"));
objNode.put("observation", (String) list.get(0).get("observation"));
ArrayNode array = new ObjectMapper().createArrayNode();
for ( Map < String , Object > myObj : list ) {
ObjectNode node = new ObjectMapper().createObjectNode();
node.put("id", (Long) myObj.get("idOrigin"));
node.put("up", (String) myObj.get("state));
node.put("series", (String) myObj.get("local"));
node.put("number", (Long) myObj.get("number"));
array . add ( node ) ;
} }
lotNode.set("input", array);
newList . add ( node ) ;
} }
String jsonOutput = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(newList);
在这种情况下使用Map比使用List更有意义,有人有更好的实现方法吗?
谢谢。
您可以随意使用jackson
https://github.com/FasterXML/jackson .
无论如何,使用jackson向Map发出反序列化JSON数组可能会有帮助。
顺便说一下,对于大多数用例,方法ObjectMapper#readValue
应该足够了。
例如:
public <T> T readValue(String content, TypeReference<T> valueTypeRef);
你可以将json
字符串反序列化成任何你想要的类:
//...
public static final ObjectMapper MAPPER = new ObjectMapper();
//... to deserialize to List<Map<String,Object>>
MAPPER.readValue(jsonString, new TypeReference<List<Map<String,Object>>>(){});
如果有什么需要更新的,请告诉我。