使用RestTemplate时如何配置内部Jackson映射器?

我想更新Spring RestTemplate所使用的jackson映射器的SerializationConfig.Feature …属性,任何想法都知道如何获得它或在哪里可以/应该对其进行配置。

回答:

默认RestTemplate构造函数注册一组HttpMessageConverter

this.messageConverters.add(new ByteArrayHttpMessageConverter());

this.messageConverters.add(new StringHttpMessageConverter());

this.messageConverters.add(new ResourceHttpMessageConverter());

this.messageConverters.add(new SourceHttpMessageConverter());

this.messageConverters.add(new XmlAwareFormHttpMessageConverter());

if (jaxb2Present) {

this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());

}

if (jacksonPresent) {

this.messageConverters.add(new MappingJacksonHttpMessageConverter());

}

if (romePresent) {

this.messageConverters.add(new AtomFeedHttpMessageConverter());

this.messageConverters.add(new RssChannelHttpMessageConverter());

}

MappingJacksonHttpMessageConverter轮流,造成ObjectMapper直接实例。你可以找到该转换器并替换ObjectMapper或注册一个新的转换器。这应该工作:

@Bean

public RestOperations restOperations() {

RestTemplate rest = new RestTemplate();

//this is crucial!

rest.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());

return rest;

}

@Bean

public MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {

MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();

converter.setObjectMapper(myObjectMapper());

return converter;

}

@Bean

public ObjectMapper myObjectMapper() {

//your custom ObjectMapper here

}

在XML中,遵循以下原则:

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

<property name="messageConverters">

<util:list>

<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>

<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>

<bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>

<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>

<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>

<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>

<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

<property name="objectMapper" ref="customObjectMapper"/>

</bean>

</util:list>

</property>

</bean>

<bean id="customObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>

请注意,转换并不是真正的1:1-我必须显式地messageConverters以XML 创建列表,而采用@Configuration这种方法,我可以引用现有列表并直接对其进行修改。但这应该可行。

以上是 使用RestTemplate时如何配置内部Jackson映射器? 的全部内容, 来源链接: utcz.com/qa/427258.html

回到顶部