Антон Антонов Антон Антонов - 1 year ago 60
JSON Question

Derive the exact class from the wrapping class Jackson

Lets assume that we have the following structure:

class BaseClass {
String typeOfSomeClass;
SomeClassBasedOnType someClassBasedOnType;

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.PROPERTY, property="BaseClass.typeOfSomeClass")
@Type(value = SomeClassBasedOnTypeImpl1.class, name="type1"),
@Type(value = SomeClassBasedOnTypeImpl2.class, name="type2")
interface SomeClassBasedOnType {
class SomeClassBasedOnTypeImpl1 implements SomeClassBasedOnType {
String str1;
class SomeClassBasedOnTypeImpl2 implements SomeClassBasedOnType {
String str2;

With the above structure I want to store a JSON using Jackson. The two possible JSONs that I need to parse are:

{"typeOfSomeClass":"type1", "someClassBasedOnType": {"str1":"someValue"}}


{"typeOfSomeClass":"type2", "someClassBasedOnType": {"str2":"someValue"}}

Here is my code that I use to deserialize the JSON:

BaseClass baseClass = new ObjectMapper().readValue(someJsonAsString, BaseClass.class);

The only thing is that I don't know how to get the type from the "base" JSON. The syntax:
still looks for a property in the SomeClassBasedOnType implementing class. Any ideas how to specify that I need the property from the wrapping class ?

Just to clarify the "base" JSON contains many keys, which are all the same including the key someClassBasedOnType. The key someClassBasedOnType however may contain two different JSON objects(with different keys) and the way to distinguish those objects is based on the value of the key in the "base" JSON called typeOfSomeClass.

Answer Source

Here is the solution for my problem, however the JsonTypeInfo.As.EXTERNAL_PROPERTY is since 1.9 version :(

Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download