【问题标题】:Jackson: "Unexpected token (VALUE_STRING), expected FIELD_NAME:" when deserializing empty string instead of expected object杰克逊:“意外的令牌(VALUE_STRING),预期的FIELD_NAME:”反序列化空字符串而不是预期的对象时
【发布时间】:2013-11-04 09:57:03
【问题描述】:

我正在使用 Jackson 反序列化来自我不拥有的服务器的 json 响应。我正在使用 JsonTypeInfo 注释来处理多态数据类型。这是我的基本类型的配置(在本例中为Thing):

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Thing.class, name = "Thing"),
        @JsonSubTypes.Type(value = FancyThing.class, name = "FancyThing")
})

一切正常,直到服务器返回一个空字符串,我期待其中一种类型,然后我得到其中一种:

org.codehaus.jackson.map.JsonMappingException: Unexpected token (VALUE_STRING), expected FIELD_NAME: missing property 'type' that is to contain type id (for class com.stackoverflow.Thing)

有没有推荐的处理这种情况的方法?就像我说的,我不控制服务器,所以我必须处理这个客户端。我宁愿通过配置ObjectMapper 来处理这个问题,但是ObjectMapper#configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) 似乎并没有像我预期的那样工作。有什么想法吗?

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    好的,所以有时要得到答案,只需问自己正确的问题。事实证明,我认为我正在查看较旧版本的 javadocs,因为我发现了@JsonTypeInfo#defaultImpl,这让我走上了正确的道路。

    现在我有一些看起来像这样的东西:

    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "type"
            defaultImpl = EmptyThing.class)
    @JsonSubTypes({
            @JsonSubTypes.Type(value = Thing.class, name = "Thing"),
            @JsonSubTypes.Type(value = FancyThing.class, name = "FancyThing")
    })
    public class Thing {
    
    ...
    
    }
    
    public class EmptyThing extends Thing {
    
        public EmptyThing(String s) {
            // Jackson wants a single-string constructor for the default impl
        }
    }
    

    【讨论】:

    • 使用带参数的构造函数又不想使用空构造函数怎么办?
    猜你喜欢
    • 2017-05-27
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2023-03-04
    • 2018-10-19
    相关资源
    最近更新 更多