是的,它可以用于抽象类和接口。
考虑以下代码示例
假设我们有一个 enum 、 interface 和 classes
enum VehicleType {
CAR,
PLANE
}
interface Vehicle {
VehicleType getVehicleType();
String getName();
}
@NoArgsConstructor
@Getter
@Setter
class Car implements Vehicle {
private boolean sunRoof;
private String name;
@Override
public VehicleType getVehicleType() {
return VehicleType.Car;
}
}
@NoArgsConstructor
@Getter
@Setter
class Plane implements Vehicle {
private double wingspan;
private String name;
@Override
public VehicleType getVehicleType() {
return VehicleType.Plane;
}
}
如果我们尝试将这个 json 反序列化为List<Vehicle>
[
{"sunRoof":false,"name":"Ferrari","vehicleType":"CAR"},
{"wingspan":19.25,"name":"Boeing 750","vehicleType":"PLANE"}
]
然后我们会得到错误
abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
要解决这个问题,只需在界面中添加以下JsonSubTypes
和JsonTypeInfo
注释,如下所示
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
property = "vehicleType")
@JsonSubTypes({
@JsonSubTypes.Type(value = Car.class, name = "CAR"),
@JsonSubTypes.Type(value = Plane.class, name = "PLANE")
})
interface Vehicle {
VehicleType getVehicleType();
String getName();
}
有了这个,反序列化将与接口一起工作,你会得到List<Vehicle>
回报
您可以在此处查看代码 - https://github.com/chatterjeesunit/java-playground/blob/master/src/main/java/com/play/util/jackson/PolymorphicDeserialization.java