从 Location 扩展的类 AddressLocation 和 AirportLocation。当 json 中的“type”字段作为“ADDRESS”或“AIRPORT”出现时,jackson 正确地将其分别反序列化为 AddressLocation 和 AirportLocation 类。当“type”不存在时,jackson 不知道如何反序列化该对象。有没有一种方法可以配置杰克逊,如果“类型”不存在或为空,则使用默认类型作为“地址”?//从以下内容中删除了 getters、setters 和构造函数@JsonInclude(value= JsonInclude.Include.NON_EMPTY)@JsonIgnoreProperties(ignoreUnknown = true)@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible=false)@JsonSubTypes({ @JsonSubTypes.Type(value = AirportLocation.class, name = "AIRPORT"), @JsonSubTypes.Type(value = AddressLocation.class, name = "ADDRESS")})public abstract class Location { private List<Float> geoCoordinates; private String city; private String countryCode; }public class AddressLocation extends Location { private String province; private String postalCode; private String streetAddress; public AddressLocation(final List<Float> geoCoordinates, final String city, final String countryCode, final String province, final String postalCode, final String streetAddress) { super(geoCoordinates, city, countryCode); this.province = province; this.postalCode = postalCode; this.streetAddress = streetAddress; }}public class AirportLocation extends Location { String airportCode;}我得到的错误是 -Missing type id when trying to resolve subtype of [simple type, class ***]: missing type id property 'type' at [Source: (String)"{"geo_coordinates":[1.17549435E-38],"city":"Whateverville","country_code":"WW"}"; line: 1, column: 79]
1 回答
九州编程
TA贡献1785条经验 获得超4个赞
当 JSON 由客户端发送并由控制器等框架反序列化时,我遇到了类似的问题。如果是这种情况,那是因为框架管理的 Jackson 不是由您的代码管理的。您可以通过注入自定义反序列化器,也可以通过传输对象简单地控制代码中的所有实例初始化
@POST
public String createAddress(AddressLocationRequest requestObj) {
AddressLocation address = new AddressLocation();
BeanUtils.copyProperties(address, requestObj);
...
}
添加回答
举报
0/150
提交
取消