Polymorphism in Jackson

Celal Kartal
1 min readAug 23, 2022

--

@Getter
@Setter
@JsonIgnoreProperties
public class MyRequestDTO{
@NotNull
private Device device; //Composition
}@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({ @JsonSubTypes.Type(value = Mobil.class, name = "mobil"),
@JsonSubTypes.Type(value = Laptop.class, name = "laptop") })
public interface Device{
public String result();
}
@Getter
@Setter
@JsonTypeName("mobil")
@JsonIgnoreProperties
public class Mobil implements Device{
private boolean mobilFieldName;
@Override
public String result() {
return this.getMobilFieldName();
}
}@Getter
@Setter
@JsonTypeName("laptop")
@JsonIgnoreProperties
public class Laptop implements Device{
private String laptopFieldName;
@Override
public String result() {
return this.getLaptopFieldName();
}
}

Json Example -1:

{
"device": {
"mobil": {
"mobilFieldName": true
}
}
}

JSON Example -2

{
"device": {
"laptop": {
"laptopFieldName": "my laptop details"
}
}
}

How to use…

1- To access Mobil/Laptop object fieldsif (myRequestDTO.getDevice() instanceof Mobil) {Mobil mobil= (Mobil) myRequestDTO.getDevice();
mobil.getMobilFieldName();
}else if (myRequestDTO.getDevice() instanceof Laptop) {Laptop laptop= (Laptop) myRequestDTO.getDevice();
laptop.getLaptopFieldName();
}2- To access common methods...myRequestDTO.getDevice().getResult();

good luck…

--

--

Celal Kartal
Celal Kartal

Written by Celal Kartal

Computer Engineer | Software Developer

No responses yet