首页 文章

在ObjectMapper中全局配置JavaTimeModule而不是使用@datetimeformat

提问于
浏览
0

嗨,我尝试创建一个接受请求参数作为LocalDateTime的控制器 .

ex: /api/actions?page=0&size=10&from=2018-05-02T20:20:20&to=2018-06-02T20:20:20

在控制器,如果我使用代码下面的工作:

@RequestParam(value = "from")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
                LocalDateTime from,
        @RequestParam(value = "to")
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
                LocalDateTime to

但是我想将@DateTimeFormat移动到全局配置,我选择了ObjectMapper:

我在配置中创建了一个bean:

@Bean
public ObjectMapper jacksonObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(
            LocalDateTime.class,
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
}

并尝试

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(
            LocalDateTime.class,
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
}

这是dateTimeFormat值:yyyy-MM-dd'T'HH:mm:ss.SS

以上两种方法都不起作用,它说:

class org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:无法将类型'java.lang.String'的值转换为必需类型'java.time.LocalDateTime';嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型为'2018的类型[@ org.springframework.web.bind.annotation.RequestParam java.time.LocalDateTime] -05-02T20:20:20' ;嵌套异常是java.lang.IllegalArgumentException:值的解析尝试失败[2018-05-02T20:20:20]

我的 Jackson 版本:

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

我错过了什么吗?感谢您的时间 .

2 回答

  • 0

    问题是我在requestParam传递了LocalDateTime,但我使用的ObjectMapper只能处理请求的主体 .

    为了解决我的问题,我创建了新的组件LocalDateTimeConverter并删除了ObjectMapper的bean .

    @Component
    public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    private final DateTimeFormatter formatter;
    
    @Autowired
    public LocalDateTimeConverter(@Value("${dateTime.format}") String dateTimeFormat) {
        this.formatter = DateTimeFormatter.ofPattern(dateTimeFormat);
    }
    
    @Override
    public LocalDateTime convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }
    
        return LocalDateTime.parse(source, formatter);
    }
    }
    
  • 0

    class org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:无法将类型'java.lang.String'的值转换为必需类型'java.time.LocalDateTime';嵌套异常是org.springframework.core.convert.ConversionFailedException

    我想在这里你需要使用JsonSerializer和JsonDeserializer .

    因此,当请求到来时,您使用JsonDeserializer,它会将您的String格式的日期转换为所需的日期格式 . 这是一个代码,

    @Component
    public class DateDeSerializer extends JsonDeserializer<Date> {
    
        public final SimpleDateFormat formatter = new SimpleDateFormat("date format");
    
        @Override
        public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
            if (jp.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
                try {
                    return formatter.parse(jp.getText());
                } catch (ParseException e) {
                    // throw exception 
                }
            }
            return null;
        }
    
        @Override
        public Class<Date> handledType() {
            return Date.class;
        }
    
    }
    

    要格式化您的响应,请使用JsonSerializer . 这是一个示例代码,

    @Component
    public class DateSerializer extends JsonSerializer<Date> {
    
        DateFormat formatter = new SimpleDateFormat("date format");
    
        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeObject(formatter.format(value));
        }
    
        @Override
        public Class<Date> handledType() {
            return Date.class;
        }
    
    }
    

相关问题