Spring:在REST响应中格式化日期,而无需修改域类

时间:2019-02-21 10:40:12

标签: spring date jackson

我有一个Spring 5(非Spring Boot)项目,该项目的端点返回在依赖项jar中定义的对象(我无法对其进行修改)。该对象的字段为日期(LocalDateTime)。

日期在响应中的格式如下:

{
    "dayOfMonth": 21,
    "dayOfWeek": "THURSDAY",
    "month": "FEBRUARY",
    "year": 2019,
    "dayOfYear": 52,
    "hour": 11,
    "minute": 24,
    "nano": 753000000,
    "second": 32,
    "monthValue": 2,
    "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
    }
}

我该如何写成ISO 8601或类似版本?我尝试添加以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
    <version>2.9.8</version>
</dependency>

我还尝试为ObjectMapper创建一个主bean:

@Bean
@Primary
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    return objectMapper;
}

在显式使用映射器时工作正常,但在Spring返回JSON REST响应时无法使用。

为简化而不是编写整个代码,我希望以下端点这样隐式正确地设置日期格式。

    @GetMapping(path = "/date", produces = "application/json")
    public @ResponseBody ResponseEntity<LocalDateTime> date(@RequestHeader HttpHeaders headers) {
        return new ResponseEntity<>(LocalDateTime.now(), HttpStatus.OK);
    }

谢谢。

1 个答案:

答案 0 :(得分:0)

我通过添加一个Configuration类来修复它,该类基于此blog entry将我的ObjectMapper链接到HTTPMessageConverter。

@Configuration
public class JacksonConfiguration {

    @Autowired
    ObjectMapper mapper;

    private RequestMappingHandlerAdapter annotationMethodHandlerAdapter;

    @PostConstruct
    public void init() {
        List<HttpMessageConverter<?>> messageConverters = annotationMethodHandlerAdapter.getMessageConverters();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter m = (MappingJackson2HttpMessageConverter) messageConverter;
                m.setObjectMapper(mapper);
            }
        }
    }

    @Autowired
    public void setAnnotationMethodHandlerAdapter(RequestMappingHandlerAdapter annotationMethodHandlerAdapter) {
        this.annotationMethodHandlerAdapter  = annotationMethodHandlerAdapter;
    }
}