RestTemplate——解决Date类型值自动转为时间戳问题
1. 问题描述
使用RestTemplate发送post请求,传参为pojo类集合,pojo类中有Date
数据类型的字段。原本时间值为yyyy-MM-dd HH:mm:ss
格式,但接收端收到的是时间戳格式。
@Autowired
protected RestTemplate restTemplate;
List<User> list = new ArrayList<>();
User user = new User();
user.setCreateTime(new Date());
list.add(user);
restTemplate.postForObject(url, list, JSONObject.class);
2. 网上答案
-
加配置
spring: jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss
配置原本就存在了,所以这个答案无效。
-
在字段上添加
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
这个字段的作用是在转换成JSON的时候规定时间格式,跟当前问题无直接关系。
但是可以通过先转换为JSON字符串,然后将JSON字符串做为参数去请求,这样是可以解决自动转时间戳问题的
String params = JSON.toJSONString(list); restTemplate.postForObject(url, params, JSONObject.class);
但这样就需要在每个pojo类的Date数据类型字段上面添加注解,并不是很好的解决方法,这里寻找可以全局设定的解决方案。
3. 解决路程
-
确定是发送端还是接收端转换成时间戳的
在
restTemplate.postForObject()
发送请求时打断点,可以看到参数已经是时间戳了,所以确定是在发送端将参数转换成了时间戳。 -
restTemplate.postForObject()打断点分析是哪里改成了时间戳
源码关键代码:
@Nullable public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = this.httpEntityCallback(request, responseType); HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger); return this.execute(url, HttpMethod.POST, requestCallback, responseExtractor, (Object[])uriVariables); } public HttpEntityRequestCallback(@Nullable Object requestBody, @Nullable Type responseType) { super(responseType); if (requestBody instanceof HttpEntity) { this.requestEntity = (HttpEntity)requestBody; } else if (requestBody != null) { this.requestEntity = new HttpEntity(requestBody); } else { this.requestEntity = HttpEntity.EMPTY; } } @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientExceptio