Skip to content
Advertisement

JSON data mapping in Java with Jackson

I got stuck in mapping a json into my data structures “the easy way” using just Jackson decorators and I was wondering if there is a way to do this …

The json that I try to read has the following structure:

JavaScript

So basically every data entity has a “data_info” object (mapped in my code from below to DataTypeInfo) that has a property “ns” object (mapped in my code TypeInfo) which contains the object type. So this means that the discriminator for object types is always under data_info.ns

Here are my data entities:

JavaScript

The error in my code is in the discriminator from the Mammals class: property = “data_info.ns” since this is intended to work with properties but I try to use a sub property … Is there a way to correctly declare the discriminator of the Mammal abstract class so that the correct Dog or Cat objects are instantiated ?

Advertisement

Answer

The solution that I ended up with was to use a custom builder (JsonCreator) in the abstract class (for the example from above Mammals).

My updated Mammals class looks like this:

JavaScript

Since my root class (Animals) contains a list of Mammals, for every element of this list this creator is executed to build the proper instance of Mammals (Cat or Dog in my example).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement