简体   繁体   English

如何使用Java Jackson将JSON数组的任意字符串解析为列表

[英]How to parse arbitrary string of JSON array to a list using Java Jackson

I am trying to use Jackson in Java to parse a string of Json Array in the format of 我正在尝试在Java中使用Jackson来解析Json Array的字符串,其格式为

"[{"key1":"value1"},{"key2":{"keyChild1":"valueChild1","keyChild2","valueChild2"}}]" 

However, the JSON object inside the string of array could be any arbitrary valid JSON, which means I cannot map them to any predefined POJO as suggested in Parsing JSON in Java without knowing JSON format 但是,数组字符串中的JSON对象可以是任意有效的JSON,这意味着我无法在不了解JSON格式的情况下按照Java解析JSON中的建议将它们映射到任何预定义的POJO。

The goal is to convert this string of JSON array to a List<someObject> that can represent each of the JSON inside the array, and this someObject will allow me to add/remove any key/value pairs in that JSON. 目标是将JSON数组的字符串转换为可以表示数组内部每个JSON的List<someObject> ,并且此someObject将允许我添加/删除该JSON中的任何键/值对。

I have tried to use 我尝试使用

final ObjectMapper objectMapper = new ObjectMapper();
List<JsonNode> jsonNodes = objectMapper.readValue(jsonArraytring, new TypeReference<List<JsonNode>>() {});

and it seems like the List to be empty. 并且列表似乎为空。 I really got stuck here. 我真的被困在这里。

Any help would be appreciated. 任何帮助,将不胜感激。

try 尝试

 String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
 ArrayNode array = (ArrayNode) new ObjectMapper().readTree(json);

You can deserialize the JSON array into a list of maps: 您可以将JSON数组反序列化为地图列表:

ObjectMapper mapper = new ObjectMapper();
String json = "[{\"key1\":\"value1\"},{\"key2\":{\"keyChild1\":\"valueChild1\",\"keyChild2\":\"valueChild2\"}}]";
List<Object> list = mapper.readValue(json, List.class);
list.forEach(o -> {
    System.out.println(o);
    System.out.println(o.getClass());
});

Which outpurs: 哪个胜过:

{key1=value1}
class java.util.LinkedHashMap
{key2={keyChild1=valueChild1, keyChild2=valueChild2}}
class java.util.LinkedHashMap

You can push that even further by calling mapper.readValue(json, Object.class) . 您可以通过调用mapper.readValue(json, Object.class)进一步推动这一点。 But then you'll need to know how to use the deserialized types. 但是,那么您将需要知道如何使用反序列化类型。

You can try the following: 您可以尝试以下方法:

JsonNode node = objectMapper.valueToTree(jsonArraytring);
for(JsonNode innerNode : node.elements()){
    //here you have each inner object 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM