首页 > 解决方案 > 如何使用 spring xml 将 FAIL_ON_UNKNOWN_PROPERTIES 设置为 false

问题描述

我正在尝试将收到的 json 响应反序列化为对象。我收到以下错误:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "initialized"

我知道该initialized字段的来源,但目前无法编辑对象类。相反,我想通过编辑对象映射器来关闭当遇到类中不存在的字段时抛出的异常:DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

RestTemplate用来调用网址。我正在使用的 restTemplate 实例是一个 bean,因此是一个单例,它是在这样的 xml 文件中创建的:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"
      p:interceptors-ref="rest-template-client-interceptors"/>

问题是我不确定如何通过 xml 构建 RestTemplate 将 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES 设置为 false。我是春天的新手,所以不知道从哪里开始。

有什么建议么?

标签: javaxmlspringjavabeans

解决方案


您必须配置 RestTemplate 消息转换器 (MappingJacksonHttpMessageConverter) 以使用自定义对象映射器。

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="customObjectMapper"/>
            </bean>
        </list>
    </property>
</bean>    
<bean id="customObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="customObjectMapper" />
    <property name="targetMethod" value="configure" />
    <property name="arguments"> 
        <list>
            <value type="org.codehaus.jackson.map.DeserializationConfig.Feature">FAIL_ON_UNKNOWN_PROPERTIES</value>
            <value>false</value>
        </list>
    </property>
</bean>

推荐阅读