2012-12-21 10 views
5

Ich verwende @JsonTypeInfo, um Jackson 2.1.0 anzuweisen, in der Eigenschaft 'discriminator' nach konkreten Typinformationen zu suchen. Dies funktioniert gut, aber die Diskriminatoreigenschaft wird während der Deserialisierung nicht in POJO gesetzt.@JsonTypeInfo-Eigenschaft während der POJO-Deserialisierung ignoriert

Nach Jackon der Javadoc (com.fasterxml.jackson.annotation.JsonTypeInfo.Id), es sollte:

/** 
* 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 ""; 

Hier ist ein failling Test

@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 { 
} 

Irgendwelche Ideen?

Antwort

14

Use 'sichtbar' Eigenschaft wie folgt:

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

die type-Eigenschaft wird dann aussetzen; Standardmäßig sind sie nicht sichtbar, so dass keine explizite Eigenschaft für diese Metadaten hinzugefügt werden muss.

+0

Kopieren/Einfügen von Jackson Benutzer Mailing-Liste, aber das ist in Ordnung. –

+4

Ja; hauptsächlich zum Vorteil von Lesern, die nicht auf der Liste stehen. – StaxMan

+2

Gibt es eine Möglichkeit, es in Jackson 1.9 zu tun? – bananasplit

Verwandte Themen