Jackson from json to class via interface

Viewed 149

I have class

public class Car() {

  @JsonProperty("type")
  private String type;

  @JsonProperty("configuration")
  @JsonDeserialize(using = AlertRuleConfigurationDeserialize.class)
  private Configuration config;
}

Configuration is interface which have 3 classes. How can I deserialize Car from json via type? If I have String type = "type1", I should deserialize to ConfigurationImplFirst, etc. I read this answer, but property = "type" inside Configuration, but I have outside. And because of it, I can't use @JsonDeserialize above property, because I have no information about type

1 Answers

Try doing the following for serialize/deserialize polymorphic objects:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes(
    @JsonSubTypes.Type(value = AlertRuleConfigurationDeserialize.class, name = "config")
)
public abstract class Car {

    private String type;
    private Configuration config;

}

Then, as an example, you can serialize/deserialize like:

public class Test {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        Configuration config = new AlertRuleConfigurationDeserialize();

        Car car = new Car("type",config);

        try {
            String carJson = objectMapper.writeValueAsString(car);

            System.out.println(carJson);

            Car deserializedCar = objectMapper.readValue(carJson, Car.class);

            System.out.println("Deserialized CarJson Class: " + deserializedCar.getClass().getSimpleName());

           
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
Related