0

Is there a way to deserialize the given JSON string with jackson so that the atttribute attr is of type Sub instead of Base?

Json:

{
    "x": "yz",
    "attr": {
        "b": "hello",
        "c": "world"
    }
}

Java Classes:

public class ExampleClass {
  String x;
  Base attr;

  //getter, setter
}


public class Base{  
  String a; 

  //getter, setter 
}

public class Sub extends Base{  
  String b;
  String c;

  //getter, setter
}
smartwepa
  • 311
  • 1
  • 3
  • 11
  • 1
    Take a look on [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance). If you can not modify this `JSON` and add for example `type` attribute which will define type of given property you can not reuse implemented features but you can always write your own deserialiser. – Michał Ziober Mar 22 '19 at 14:55

1 Answers1

0

Option 1: Fixed Implementation

Following the assumption that you have access to the implementation of Base, you can annotate it to always deserialize as the Sub implementation using JsonDeserialize.as().

@JsonDeserialize(as = Sub.class)
class Base {
    //etc.
}

Option 2: Content-based Implementation

Use a field to determine which implementation to deserialize as. See related answer for details: Deserializing polymorphic types with Jackson

Option 3: When Base Isn't Accessible

This is a way to achieve behavior like option 1 and 2 without having access to the Base class implementation. Assuming we want to achieve this with native Jackson, rather than a custom deserializer, we use Mix-ins. Mix-ins let you add annotations to a model you didn't define, by defining them on a matching signature in a different model.

To define the mix-in to produce Option 1 above:

@JsonDeserialize(as = Sub.class)
class BaseMixIn { }

And to use BaseMixIn, you must modify your ObjectMapper instance:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Base.class, BaseMixIn.class);

Simply use the mapper like any other ObjectMapper.

Bit Fracture
  • 651
  • 1
  • 9
  • 24