【问题标题】:Spring: formatting a date in a REST response without modifying the domain classSpring:在 REST 响应中格式化日期而不修改域类
【发布时间】:2019-02-21 10:40:12
【问题描述】:

我有一个 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);
    }

谢谢。

【问题讨论】:

  • 您的ObjectMapper 似乎没问题,包括模块注册。您确定这是实际用于序列化响应负载的 ObjectMapper 实例吗?
  • 我不确定,但我真的不知道如何检查。我需要将 ObjectMapper 注册为 Jackson 的默认对象映射器吗?

标签: spring date jackson


【解决方案1】:

我通过添加一个配置类来修复它,该类将我的 ObjectMapper 链接到基于此 blog entry 的 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;
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多