5
我使用@JsonTypeInfo指示Jackson 2.1.0在'discriminator'屬性中查找具體的類型信息。這很有效,但是在反序列化過程中,歧義屬性並未設置爲POJO。@JsonTypeInfo屬性在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 "";
這裏是一個failling測試
@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 {
}
任何想法?
從傑克遜用戶郵件列表複製/粘貼,但沒關係。 –
是的;主要是爲了不在名單上的讀者的利益。 – StaxMan
傑克森1.9有沒有辦法做到這一點? – bananasplit