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"
}
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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With