我有一个给定的场景:这是我正在实现的接口:
@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')`
看起来杰克逊是在DeviceType上搜索一个它当然没有的类型属性。如何告诉Jackson枚举选择基于枚举值(COMPUTER、FLASH_DRIVE)?
发布于 2018-10-25 05:48:43
我认为,仅仅通过给一堆东西指定相同的字段和属性名称,就会有太多的级别为您所折叠。
当前设置所需的JSON为:
String info = "{\"type\": {\"type\": \"COMPUTER\", \"COMPUTER\": null}}";
在这里,外部的“类型”用于DeviceInformation,内部的“类型:计算机”对用于MasterDevice的DeviceType多态性。最后一个“计算机”是实例化MasterDevice.COMPUTER (这最后一点奇怪之处感觉就像是Jackson实现的一个bug )。
为了让事情变得更清楚,这里有一个简化的版本,但进行了一些重命名:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = MasterDevice.class, name = "MASTER"),
@JsonSubTypes.Type(value = SlaveDevice.class, name = "SLAVE"),
})
interface DeviceType {
}
public enum MasterDevice implements DeviceType {
LAPTOP, SERVER;
}
public enum SlaveDevice implements DeviceType {
FLASH_DRIVE, WEBCAM;
}
public class DeviceInformation {
public DeviceType deviceType;
}
然后:
String info = "{\"deviceType\": {\"type\": \"MASTER\", \"SERVER\": null}}";
ObjectMapper mapper = new ObjectMapper();
DeviceInformation deviceInfo = mapper.readValue(info, DeviceInformation.class));
如果你想要更优雅的东西,那么你可能需要一个定制的序列化程序。
https://stackoverflow.com/questions/52973015
复制相似问题