@XmlJavaTypeAdapter不与Jackson JSON合作

时间:2012-10-18 03:16:52

标签: json spring-mvc jaxb jackson

我正在使用Spring REST框架和Jackson 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 个答案:

答案 0 :(得分: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);