Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Json array to individual Json elements using Jackson

Is there any way to split a given Json array to individual Json elements using Jackson library? Say for example, I have this Json array:

[
    {
        "key1":"value11", 
        "key2":"value12"
    },
    {
        "key1":"value21", 
        "key2":"value22"
    }
]

After splitting I want a list of individual elements like:

{
        "key1":"value11", 
        "key2":"value12"
}

and

{
        "key1":"value21", 
        "key2":"value22"
}
like image 579
Ram Bavireddi Avatar asked Dec 14 '22 16:12

Ram Bavireddi


2 Answers

A nice solution for this problem is simply to iterate by using the Java 8 Streaming API:s. The JsonNode object is Iterable where the spliterator method is available. So, the following code can be used:

public List<String> split(final String jsonArray) throws IOException {
    final JsonNode jsonNode = new ObjectMapper().readTree(jsonArray);
    return StreamSupport.stream(jsonNode.spliterator(), false) // Stream
            .map(JsonNode::toString) // map to a string
            .collect(Collectors.toList()); and collect as a List
}

Another alternative is to skip the remapping (the call to toString) and return a List<JsonNode> elements instead. That way you can use the JsonNode methods to access the data (get, path and so on).

like image 82
wassgren Avatar answered Apr 27 '23 01:04

wassgren


Finally, I found a solution that works:

public List<String> split(String jsonArray) throws Exception {
        List<String> splittedJsonElements = new ArrayList<String>();
        ObjectMapper jsonMapper = new ObjectMapper();
        JsonNode jsonNode = jsonMapper.readTree(jsonArray);

        if (jsonNode.isArray()) {
            ArrayNode arrayNode = (ArrayNode) jsonNode;
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode individualElement = arrayNode.get(i);
                splittedJsonElements.add(individualElement.toString());
            }
        }
        return splittedJsonElements;
}
like image 26
Ram Bavireddi Avatar answered Apr 27 '23 01:04

Ram Bavireddi