Home > Enterprise >  Passing 2 type of class object in spring boot controller
Passing 2 type of class object in spring boot controller

Time:11-25

I have to pass 2 different type of objects of type apple or of type orange in RequestBody in my Spring Boot Controller method.

public myResponse myMethod(@ApiParam(value = "myRequest", required = true) @RequestBody Object mulRequest) {

In above code snippet, the mulRequest of type Object can be either of Class apple or Class orange.

I want to follow something like below logic for my requirement -

if (mulRequest instanceof apple) {
// process logic...
} else if (mulRequest instanceof orange) {
// process...
}

But I am stuck on how to cast to relevant class objects based on RequestBody passed, since I will not be knowing what type of object is getting passed for mulRequest which can be of either apple or orange class. Both apple and orange class implement the Serializable interface.

Appreciate any suggestion or ways to solve this.

CodePudding user response:

What you are looking for are @JsonTypeInfo and @JsonSubTypes Jackson annotations that are adding a support for polymorphizm on deserialization.

To make Jackson understand how it should deserialize JSON object you may need to provide some additional property or add class name when serializing object - it depends on the strategy of the deserialization you will decide to use.

The example implementation of your DTO and the Controller may look like:

@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Apple.class, name = "apple"),
    @JsonSubTypes.Type(value = Orange.class, name = "orange")
})
public abstract class Fruit implements Serializable { // basically you do not need this Serializable at all here
    String someData;
    //... 
    // note that we can but we do not need to define 'type' field!
    // Jackson will handle it if it will appear in JSON
}

public class Orange extends Fruit {
    //...
}

public class Apple extends Fruit {
    //...
}

Then when your JSON will look like

{
    "someData": "test",
    "type": "orange"
}

and you will provide the following Controller

public myResponse myMethod(@ApiParam(value = "myRequest", required = true) @RequestBody Fruit mulRequest) {

Then the mulRequest can be tested whether it's Apple or Orange. Of course you cannot use there Object class because you cannot annotate it with Jackson annotations however maybe providing custom deserializer you would be able to implement this. But it would be very very fishy

Please read the following articles to understand this better:

  • Related