SpringBoot RestTemplate忽略spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false

时间:2017-11-10 12:37:29

标签: json spring-mvc spring-boot jackson

我正在使用OffsetDateTime对象。

我想以ISO格式输出这个类型,所以我已经将上述属性添加到我的application.yml中,当我在我的控制器中使用它时它工作正常。

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Schedule
{
    private OffsetDateTime time;
    private String mode;
}

在我的控制器中使用:

public ResponseEntity taskManagerTest() {
    Schedule bpTaskManagerRequest = new Schedule();

    return ResponseEntity.status(HttpStatus.CREATED).headers(null).body(bpTaskManagerRequest);
}

我返回对象时的示例结果:

{
  "time": "2017-11-12T15:03:05.171Z",
  "mode": "eSetTime"
}

但是如果我使用相同的对象在我的Spring服务中使用RestTemplate进一步发送它:

    HttpEntity<Schedule> httpEntity = new HttpEntity<>(bpTaskManagerRequest, headers);

    ResponseEntity<String> answer = restTemplate.exchange(bpTaskManagerURL, HttpMethod.POST, httpEntity,
            String.class);

序列化为:

{
    "time": 1510498985.171000000,
    "mode": "eSetTime"
}

我的RestTemplate定义为:

@Autowired
private RestTemplate restTemplate;

application.yml片段:

spring:
    jackson:
        serialization:
            write-dates-as-timestamps: false

build.gradle片段:

buildscript {
    ext {
        springBootVersion = '1.5.4.RELEASE'
        ext.kotlin_version = '1.1.51'
    }
}
compile('com.fasterxml.jackson.module:jackson-module-parameter-names')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jdk8')
compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310')

示例项目:https://github.com/deepres/OffsetDateTime-with-RestTemplate

1 个答案:

答案 0 :(得分:8)

您的应用程序正在创建自己的RestTemplate bean,而不对其应用任何自定义。这意味着它将使用默认的消息转换器和默认的Jackson配置,而不是Spring Boot配置的任何内容。

作为described in the reference documentation,Spring Boot提供了RestTemplateBuilder,可用于创建RestTemplate。它“将确保将合理的HttpMessageConverters应用于RestTemplate实例”。您可以通过将WebConfiguration更改为以下内容来更新您的示例以使用它:

package com.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;

@Configuration
public class WebConfiguration {

    @Bean
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

}

有了这个改变,转换现在是一致的:

2017-11-17 12:35:02.892  INFO 28527 --- [nio-8080-exec-2] com.example.demo.ExampleController       : Rest template: {"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}
2017-11-17 12:35:02.905  INFO 28527 --- [nio-8080-exec-1] com.example.demo.DemoService             : Object mapper:{"label":"test from controller","time":"2017-11-17T12:35:02.821Z"}