杰克逊反序列化为默认子类型

从 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]


qq_遁去的一_1
浏览 167回答 1
1回答

九州编程

当 JSON 由客户端发送并由控制器等框架反序列化时,我遇到了类似的问题。如果是这种情况,那是因为框架管理的 Jackson 不是由您的代码管理的。您可以通过注入自定义反序列化器,也可以通过传输对象简单地控制代码中的所有实例初始化@POSTpublic String createAddress(AddressLocationRequest requestObj) {&nbsp; &nbsp;AddressLocation address = new AddressLocation();&nbsp; &nbsp;BeanUtils.copyProperties(address, requestObj);&nbsp; &nbsp;...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java