2012-10-18 83 views
3

我使用Spring REST框架和傑克遜JSON@XmlJavaTypeAdapter不與傑克遜JSON工作

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
<property name="objectMapper" ref="customObjectMapper" /> 
<property name="supportedMediaTypes" value="application/json" /> 
</bean> 
<bean id="customObjectMapper"class="com.rackspace.payment.webapp.utils.JaxbJacksonObjectMapper" /> 

public class JaxbJacksonObjectMapper extends ObjectMapper { 
    @SuppressWarnings("deprecation") 
    public JaxbJacksonObjectMapper() { 
     final AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); 

     this.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true); 
     super.getDeserializationConfig().withAnnotationIntrospector(introspector); 

     this.configure(org.codehaus.jackson.map.SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false); 
     this.configure(org.codehaus.jackson.map.SerializationConfig.Feature.WRAP_ROOT_VALUE, true); 
     super.getSerializationConfig().withAnnotationIntrospector(introspector); 
    } 
} 


//JXAB element 
@XmlAttribute(name = "createDate") 
@XmlJavaTypeAdapter(CustomDateAdapter.class) 
protected Date createDate; 

我所面臨的問題是,將顯示JSON輸出時「CREATEDATE」元素的顯示如同串XML適配器類不會被調用,但它在XML輸出中工作正常。

我錯過了什麼?如何以JSON格式調用XmlJavaTypeAdapter。

+1

解決了這個問題,這個環節的幫助http://stackoverflow.com/questions/9517189/spring-mvc-and-jackson-mapping-do-not-return-the-root-element-in -json – spal

回答

0

下面的代碼爲我做了伎倆。

ObjectMapper objectMapper = new CustomObjectMapper(ENTITY_WITH_ID_DESERIALIZER); 

    AnnotationIntrospector primary = new JacksonAnnotationIntrospector(); 
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(); 
    AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary); 

    objectMapper.setAnnotationIntrospector(pair); 

    objectMapper.configure(DeserializationConfig.Feature.USE_ANNOTATIONS, true);