问题描述:
在使用RestTemplate发送POST请求时,发现发送的数据并未按配置的@JSONField转换,导致服务方一直收不到参数
排查过程:
将itemList改成Items传输即可
原因分析:
RestTemplate有默认的转换器,所以配置@JSONField 没有作用
解决办法:
修改RestTemplate默认的转换器、或者将变量名改为Items
package com.rimag.adapter.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
/**
* @author: hong
* @date: 2024/6/18 10:25
* @description
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
// 设置超时时间
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(3000);
httpRequestFactory.setConnectTimeout(3000);
httpRequestFactory.setReadTimeout(3000);
RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
//换上fastjson
List<HttpMessageConverter<?>> messageConverters= restTemplate.getMessageConverters();
Iterator<HttpMessageConverter<?>> iterator=messageConverters.iterator();
while(iterator.hasNext()){
HttpMessageConverter<?> converter=iterator.next();
//原有的String是ISO-8859-1编码 去掉
if(converter instanceof StringHttpMessageConverter){
iterator.remove();
}
//由于系统中默认有jackson 在转换json时自动会启用 但是我们不想使用它 可以直接移除
if(converter instanceof GsonHttpMessageConverter || converter instanceof MappingJackson2HttpMessageConverter){
iterator.remove();
}
}
messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
// 添加 FastJsonHttpMessageConverter,优先级高于默认的 MappingJackson2HttpMessageConverter,否则RestTemplate发送请求转换不会按@JSONField注解
messageConverters.add(fastJsonHttpMessageConverter);
return restTemplate;
}
}