通过MessageConverters对Instant进行Spring Boot序列化

时间:2018-10-09 21:02:36

标签: java spring spring-boot resttemplate jackson-databind

我试图弄清楚如何在RestTemplate的默认MessageConverters中配置ObjectMapper,以将Instants序列化为ISO 8601格式的String而不是数字。我希望避免注释模型中的每个Instant。

@SpringBootApplication
@RestController
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @PostMapping("/test")
    public String get(@RequestBody String object) {
        return object;
    }

    public String send(TestObject object) {
        return new RestTemplateBuilder().rootUri("http://localhost:8080").defaultMessageConverters().build()
            .exchange("/test", HttpMethod.POST, new HttpEntity<>(object, headers()), String.class).getBody();
    }

    private HttpHeaders headers() {
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return httpHeaders;
    }

    @AllArgsConstructor
    @Getter
    @Setter
    public static class TestObject {
        private Instant test;
    }
}

鉴于上面的代码,我希望此测试通过

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@RunWith(SpringRunner.class)
public class InstantTest {

    @Autowired
    private DemoApplication client;

    @Test
    public void name() {
        final String time = "2018-10-09T12:00:00.000Z";
        final String response = client.send(new DemoApplication.TestObject(Instant.parse(time)));
        assertThat(response).contains(time);
    }
}

该示例使用jackson 2.9.6和Spring Boot 2.0.5。 我已经尝试过

  • 在自动配置的ObjectMapper上禁用WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS
  • 使用spring.jackson.serialization.write_date_timestamps_as_nanoseconds = false
  • 提供Jackson2ObjectMapperBuilderCustomizer @Bean禁用WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS
  • 提供自定义的Jackson2ObjectMapperBuilder

我显然缺少了某些东西,因为这感觉应该是默认行为,或者至少很容易配置。

1 个答案:

答案 0 :(得分:0)

您可以使用Custom RestTemplateBuilder创建自己的RestTemplate并实现它。

例如

@Configuration
public class Config{
    @Bean
    public RestTemplate  restTemplate() {
        RestTemplateBuilder builder = new RestTemplateBuilder();
        //You can initialize your custom message converter here;
        HttpMessageConverter<?> messageConverters = new  MappingJackson2HttpMessageConverter();
        builder.messageConverters(messageConverters);
        return builder.build();
    }
}

您可以拥有自己的MessageConvertor来将实例序列化为ISO 8601。

要进一步阅读,请遵循此link