【发布时间】:2018-10-24 15:40:14
【问题描述】:
我有给定的情况: 这是我正在实现的接口:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = MasterDevice.class, name = "COMPUTER"),
@JsonSubTypes.Type(value = SlaveDevice.class, name = "FLASH_DRIVE"),
})
interface DeviceType{
String getName();
}
接口被两个枚举使用:
public enum MasterDevice implements DeviceType{
COMPUTER("Computer");
private String name;
public MasterDevice(String name){
this.name=name;
}
@Override public String getName(){return this.name;}
}
第二个是您可以附加到MasterDevice 的设备。
public enum SlaveDevice implements DeviceType{
FLASH_DRIVE("USB Drive");
private String name;
public SlaveDevice(String name){
this.name=name;
}
@Override public String getName(){return this.name;}
}
我要反序列化的POJO是:
public class DeviceInformation{
private DeviceType type;
}
而我要反序列化的 json 字符串如下所示:
String info = "{\"type\":\"COMPUTER\"}";
ObjectMapper mapper = new ObjectMapper();
DeviceInformation deviceInfo = mapper.readValue(info, DeviceInformation.class);
所有研究都建议为 DeviceType 实现一个自定义反序列化器,我不想这样做,因为它看起来很难维护。
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class DeviceType]: missing type id property '@type' (for POJO property 'type')`
Jackson 似乎在 DeviceType 上搜索了一个它当然没有的类型属性。如何告诉 Jackson Enum 选择是基于枚举值(COMPUTER、FLASH_DRIVE)?
【问题讨论】:
-
能否同时包含您的 getName() 实现和反序列化代码?
-
@DaneWhite 我包含了它。
-
您的代码仍然与出现的异常不匹配。异常表明您没有在 JsonTypeInfo 中指定 property = "type",因为它默认为 "@type"。