【问题标题】:@JsonTypeInfo property ignored during POJO deserialization在 POJO 反序列化期间忽略 @JsonTypeInfo 属性
【发布时间】:2012-12-09 05:08:38
【问题描述】:

我正在使用 @JsonTypeInfo 来指示 Jackson 2.1.0 在“鉴别器”属性中查找具体类型信息。这很好用,但是在反序列化过程中没有将鉴别器属性设置到 POJO 中。

根据 Jackon 的 Javadoc (com.fasterxml.jackson.annotation.JsonTypeInfo.Id),它应该:

/**
 * Property names used when type inclusion method ({@link As#PROPERTY}) is used
 * (or possibly when using type metadata of type {@link Id#CUSTOM}).
 * If POJO itself has a property with same name, value of property
 * will be set with type id metadata: if no such property exists, type id
 * is only used for determining actual type.
 *<p>
 * Default property name used if this property is not explicitly defined
 * (or is set to empty String) is based on
 * type metadata type ({@link #use}) used.
 */
public String property() default "";

这是一个失败的测试

 @Test
public void shouldDeserializeDiscriminator() throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    Dog dog = mapper.reader(Dog.class).readValue("{ \"name\":\"hunter\", \"discriminator\":\"B\"}");

    assertThat(dog).isInstanceOf(Beagle.class);
    assertThat(dog.name).isEqualTo("hunter");
    assertThat(dog.discriminator).isEqualTo("B"); //FAILS
}

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "discriminator")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Beagle.class, name = "B"),
        @JsonSubTypes.Type(value = Loulou.class, name = "L")
})
private static abstract class Dog {
    @JsonProperty("name")
    String name;
    @JsonProperty("discriminator")
    String discriminator;
}

private static class Beagle extends Dog {
}

private static class Loulou extends Dog {
}

有什么想法吗?

【问题讨论】:

    标签: java jackson deserialization


    【解决方案1】:

    像这样使用“可见”属性:

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "discriminator", visible=true)
    

    然后会暴露类型属性;默认情况下,它们是不可见的,因此无需为此元数据添加显式属性。

    【讨论】:

    • 从杰克逊用户邮件列表复制/粘贴,但没关系。
    • 杰克逊 1.9 有没有办法做到这一点?
    • 我不这么认为,根据 javadocs,visible 是在 2.0 中添加的。
    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 2016-05-26
    • 2013-04-07
    • 2017-06-04
    • 1970-01-01
    • 2014-06-13
    • 2021-12-18
    相关资源
    最近更新 更多