Search code examples
javajacksonobjectmapper

Jackson - Read different object one by one from file


I have a file like this:

[{
    "messageType": "TYPE_1",
    "someData": "Data"
},
{
    "messageType": "TYPE_2",
    "dataVersion": 2
}]

As you can see there is a file which contains different types of JSON objects. I also have an ObjectMapper which is able to parse the both types. I have to read the JSon objects one by one (because this file can be pretty huge) and to get the right Object (Type1Obj or Type2Obj) for each of them.

My question is how I could achieve with Jackson to read the JSon objects one by one from the file.


Solution

  • You could read the array as a generic Jackson JSON object similar to

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    

    then traverse all the children of the array using

    rootNode#elements()
    

    and parse every one of the JsonNode children into the respective type using a check of messageType similar to

    if ("TYPE_1".equals(childNode.get("messageType")) {
        Type1Class type1 = objectMapper.treeToValue(childNode, Type1Class.class);
    } else // ...