【问题标题】:How to set FAIL_ON_UNKNOWN_PROPERTIES to false using spring xml如何使用 spring xml 将 FAIL_ON_UNKNOWN_PROPERTIES 设置为 false
【发布时间】:2019-10-30 18:21:16
【问题描述】:

我正在尝试将收到的 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。我是春天的新手,所以不知道从哪里开始。

有什么建议吗?

【问题讨论】:

    标签: java xml spring javabeans


    【解决方案1】:

    您必须配置 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>
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 2019-07-06
      • 2012-08-10
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多