Ben*_*out 6 java jackson deserialization
我正在使用@JsonTypeInfo来指示Jackson 2.1.0查看'discriminator'属性中的具体类型信息.这很有效但在反序列化期间没有将鉴别器属性设置到POJO中.
根据同时杰克逊的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 "";
Run Code Online (Sandbox Code Playgroud)
这是一项令人惊叹的测试
@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 {
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?
Sta*_*Man 19
像这样使用'visible'属性:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "discriminator", visible=true)
Run Code Online (Sandbox Code Playgroud)
然后将公开type属性; 默认情况下,它们不可见,因此无需为此元数据添加显式属性.
| 归档时间: |
|
| 查看次数: |
6576 次 |
| 最近记录: |