是的,它既可以用于抽象类,也可以用于接口。
请考虑下面的代码示例
假设我们有一个枚举、接口和类
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