0

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.

  • Maybe this can help? https://stackoverflow.com/questions/44122782/jackson-deserialize-based-on-type using JsonSubTypes – Brother Jun 05 '19 at 08:57
  • Possible duplicate of [Polymorphism in jackson annotations: @JsonTypeInfo usage](https://stackoverflow.com/questions/11798394/polymorphism-in-jackson-annotations-jsontypeinfo-usage) – matanper Jun 05 '19 at 10:54
  • As I said there is no problem anymore with the two different types. The question is that how I can read one by one the JSon Objects using Jackson. (I also edited the question to make it more clear) – Arnold Robert Turdean Jun 05 '19 at 11:53

1 Answers1

0

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 // ...
Smutje
  • 17,733
  • 4
  • 24
  • 41