spring 在使用RestTemplate时,如何配置内部JacksonMap器?

cyvaqqii  于 2023-10-15  发布在  Spring
关注(0)|答案(6)|浏览(138)

我想更新SerializationConfig. configure. Spring RestTemplate使用的Jacksonmapper的属性,任何想法我可以如何获得它或者我可以/应该在哪里配置它。

xsuvu9jc

xsuvu9jc1#

默认的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 -我必须在XML中显式创建messageConverters列表,而使用@Configuration方法,我可以引用现有的列表并简单地修改它。不过,这个应该能行。

k2arahey

k2arahey2#

如果你没有使用Spring IOC,你可以这样做(Java 8):

ObjectMapper objectMapper = new ObjectMapper();
// configure your ObjectMapper here

RestTemplate restTemplate = new RestTemplate();    

MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(false);
messageConverter.setObjectMapper(objectMapper);
restTemplate.getMessageConverters().removeIf(m -> m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
restTemplate.getMessageConverters().add(messageConverter);
a0zr77ik

a0zr77ik3#

RestTemplate将初始化它的默认消息转换器。您应该用自己的bean替换MappingJackson2HttpMessageConverter,它应该使用您想要使用的对象Map器。这对我很有效:

@Bean
public RestTemplate restTemplate() {
    final RestTemplate restTemplate = new RestTemplate();

    //find and replace Jackson message converter with our own
    for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
        final HttpMessageConverter<?> httpMessageConverter = restTemplate.getMessageConverters().get(i);
        if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter){
            restTemplate.getMessageConverters().set(i, mappingJackson2HttpMessageConverter());
        }
    }

    return restTemplate;
}

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(myObjectMapper());
    return converter;
}

@Bean
public ObjectMapper myObjectMapper() {
    // return your own object mapper
}
gev0vcfq

gev0vcfq4#

完成其他答案:如果你的ObjectMapper只是注册一个JacksonModule与自定义序列化器/反序列化器,你可能想直接注册你的模块在现有的ObjectMapperRestTemplate的默认MappingJackson2HttpMessageConverter如下(例子没有DI,但同样适用于如果使用DI):

SimpleModule module = new SimpleModule();
    module.addSerializer(...);
    module.addDeserializer(...);

    MappingJackson2HttpMessageConverter messageConverter = restTemplate.getMessageConverters().stream()
                    .filter(MappingJackson2HttpMessageConverter.class::isInstance)
                    .map(MappingJackson2HttpMessageConverter.class::cast)
                    .findFirst().orElseThrow( () -> new RuntimeException("MappingJackson2HttpMessageConverter not found"));
    messageConverter.getObjectMapper().registerModule(module);

这将允许您完成原始ObjectMapper的配置(如Spring的Jackson2ObjectMapperBuilder所做的那样),而不是替换它。

t9aqgxwy

t9aqgxwy5#

使用Sping Boot ,就像这样简单:

RestTemplate template = new RestTemplateBuilder()
                            .additionalMessageConverters(new MappingJackson2HttpMessageConverter(objectMapper))
                            .build()

(用 Spring Boot 2.2.1测试)

zqry0prt

zqry0prt6#

要使用当前ObjectMapper更新SerializationConfig.特性,请执行以下操作:

RestTemplate restTemplate =  new RestTemplate();
restTemplate.getMessageConverters().forEach(mc -> {
            if (mc instanceof MappingJackson2HttpMessageConverter ) {
                //whatever you want to change
                ((MappingJackson2HttpMessageConverter) mc).getObjectMapper().setSerializationInclusion(Include.NON_NULL);
            }
        });

相关问题