9

I'm using @JsonTypeInfo to instruct Jackson 2.1.0 to look in the 'discriminator' property for concrete type information. This works well but discriminator property is no set into POJO during deserialization.

According to Jackon's Javadoc (com.fasterxml.jackson.annotation.JsonTypeInfo.Id), it should :

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

Here is a 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 {
}

Any ideas ?

Matthias
  • 7,432
  • 6
  • 55
  • 88
Benoît Guérout
  • 1,977
  • 3
  • 21
  • 30

1 Answers1

27

Use 'visible' property like so:

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

which will then expose type property; by default they are not visible so that there is no need to add explicit property for this metadata.

StaxMan
  • 113,358
  • 34
  • 211
  • 239