2012-12-21 2 views
5

저는 @JsonTypeInfo를 사용하여 Jackson 2.1.0에 구체적인 형식 정보의 'discriminator'속성을 살펴 보도록 지시합니다. 이것은 잘 작동하지만 비 직렬화 (deserialization) 중에는 discriminator 속성이 POJO에 설정되지 않습니다. JACKON의 자바 독 (com.fasterxml.jackson.annotation.JsonTypeInfo.Id)에 따르면POJO 역 직렬화 중에 @JsonTypeInfo 속성이 무시되었습니다.

, 그것은해야한다 :

여기
/** 
* 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 { 
} 

어떤 아이디어가? 그래서 같은

답변

14

사용 '볼'속성 : 입력 한 다음 속성을 노출합니다

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

; 기본적으로이 속성은 표시되지 않으므로이 메타 데이터에 대한 명시 적 속성을 추가 할 필요가 없습니다.

+0

jackson 사용자 메일 링리스트에서 복사/붙여 넣기를하고 있지만 괜찮습니다. –

+4

예; 주로 목록에없는 독자를위한 것입니다. – StaxMan

+2

잭슨 1.9에서 할 수있는 방법이 있습니까? – bananasplit