從 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
提交
取消