GentlemanHal
GentlemanHal

Reputation: 354

How do I do polymorphic JSON deserialisation with Jackson based on attribute in parent class?

We have the following Json:

{
    "type" : "1",
    "otherStuff" : "2",
    ...
    "items" : [
        {
          "commonItemAttribute" : "value",
          "specificToType1" : "whatever"
          ...
        }
    ]
}

We need to polymorphically deserialise the items into different sub classes based on the type attribute.

Is it possible in a custom Jackson deserialiser to get the type value?

Can we safely look back up the Json tree using the JsonParser given to the deserialize method?

I found this blog about polymorphic deserialisation but it seems to require a type attribute on the items themselves.

Thanks

Upvotes: 2

Views: 578

Answers (1)

StaxMan
StaxMan

Reputation: 116472

This kind of JSON is not supported, since while "External" type ids of form:

{ "childType" : "SomeTypeId", "child" : { .... } }

are supported (with @JsonTypeInfo.As.EXTERNAL_PROPERTY), they only work for simple types, not for Collections or Maps.

So if you can't change JSON to be bit more standard (including type id for elements is the standard way), you will need to use custom serializers, deserializers.

Upvotes: 1

Related Questions