0

In my Spring boot service, I have a controller as below

@PostMapping 
public ApiResponse generateUKLabel(@RequestBody LabelRequestData data){
  //do operation
}

Here, LabelRequestData has List of base class. In, request I am passing child class data with base class data. But, Child class data seems to be ignored.

Is there any way I can access the child class data. I want to make the LabelRequestData with Base class generic so that it can accept multiple child class data.

Is there any way to solve it?

I tried casting. but throws can't cast exception I also tried generics. but then I need to create two controller method to handle those request. I want only one controller method to handle the request

@Data
public class LabelRequestData extends BaseRequestData {

    @Valid
    private List<BaseClass> labelData; // this base class has multiple child classes that i need

    @Valid
    private PreferenceData preferenceData;

}
Avi
  • 1,458
  • 9
  • 14

1 Answers1

1

When Deserialising the Jackson will not know which child class that has to be used, so it only takes the value of the BaseClass and ignores the ChildClass

You could use @JsonTypeInfo in the BaseClass , this helps the Jackson to identify the proper ChildClass (You have to add type in the json)

I am not sure what BaseClass holds so I am just assuming random attributes below.

BaseClass.java

@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = ChildOne.class, name = "childOne"),
        @JsonSubTypes.Type(value = ChildTwo.class, name = "childTwo")})
public class BaseClass {
    private Integer id;
}

ChildOne .java

@Data
public class ChildOne extends BaseClass {
    private String name;
}

ChildTwo.java

@Data
public class ChildTwo extends BaseClass {
    private String address;
}

If you request the Json,

{
  "labelData": [
    {
      "id": 0,                       //      -|
      "type": "childOne",            //       |-> This will go to ChildOne.class
      "name": "Foo"                  //      _|
    }, {
      "id": 0,                       //      -|
      "type": "childTwo",            //       |-> This will go to ChildTwo.class
      "address": "Somewhere in Earth"//      _|
    }
  ]
  // Rest of Json
}
Avi
  • 1,458
  • 9
  • 14
  • This works for me. Is it possible to choose child class base on field value that belongs to PreferenceData class thats parallel to List? – Bhavesh Shah Jul 03 '19 at 10:00