0

Suppose I have a base class A:

public class A {
    public String a;
}

And two child classes B and C:

public class B extends A {
    public String b;
}

public class C extends A {
    public String c;
}

And wrapper of A class:

public class Wrapper {
    public A a;
}

And I have Rest controller that receives client requests as wrapper object:

@RestController
public class SomeController {

    public void foo(@RequestBody Wrapper wrapper) {}

}

The problem is that Jackson casts wrapper field to base class A.

How can I configure it to recieve correct type?

ivanjermakov
  • 1,131
  • 13
  • 24

1 Answers1

1

Annotate your base class A with type information that tells Jackson how to decide whether a given json object should be deserialized to B.java or C.java.

Ex: With the below code, we are telling jackson that json object for A.class will contain a property with key type whose value can be either "b" or "c". If the value is "b", deserialize the object to B.class, else deserialize it to C.class

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")  
@JsonSubTypes({  
    @Type(value = B.class, name = "b"),  
    @Type(value = B.class, name= "c")
    })  
class A {
}

Following is the json that you should be using.

{
   "a" : { // This will be deserialized to B.class
      "type": "b",
      // field of B.class
   }
}



{
   "a" : { // This will be deserialized to C.class
      "type": "c",
      // field of C.class
   }
}
Ranjith
  • 1,623
  • 3
  • 21
  • 34
  • I got it right but important thing was that base class cannot be instantiated. Base class should be `abstract` or `interface`. – ivanjermakov May 26 '18 at 17:38