0

I am trying to use Jackson in Java to parse a string of Json Array in the format of

"[{"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

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.

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.

Captain Rib
  • 285
  • 1
  • 6
  • 17
  • Does it have to be POJOs? It sounds like you're just manipulating raw json so you could just use JSONNode instead? – Hitobat Jun 07 '18 at 18:59

3 Answers3

0

try

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

You can deserialize the JSON array into a list of maps:

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). But then you'll need to know how to use the deserialized types.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

You can try the following:

JsonNode node = objectMapper.valueToTree(jsonArraytring);
for(JsonNode innerNode : node.elements()){
    //here you have each inner object 
}
NiVeR
  • 9,644
  • 4
  • 30
  • 35