java - @JsonDeserialize 注释不起作用

标签 java spring-mvc java-8 json-deserialization

@JsonDeserialize 注释不起作用时,我遇到了问题。例如,当客户端的生日值包含“12.06.1999”时,我收到 400 Bad Request http 代码响应。 这对我来说是一个非常奇怪的行为,因为 @JsonSerialize 注释效果很好!但如果我使用 @DateTimeFormat 注释而不是 @JsonDeserialize 则一切正常。

我使用 java 8,这是我的代码:

public class Person {
    @JsonProperty("birthday")
    @JsonSerialize(using = DateSerializer.class)
    @JsonDeserialize(using = DateDeserializer.class)
    private LocalDate birthday;

    // other fields, getter and setter, etc.
}

public class DateSerializer extends JsonSerializer<LocalDate> {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    @Override
    public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
        generator.writeString(formatter.format(value));
    }
}

public class DateDeserializer extends JsonDeserializer<LocalDate>{

    @Override
    public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        ObjectCodec oc = jp.getCodec();
        TextNode node = oc.readTree(jp);
        String dateString = node.textValue();

        Instant instant = Instant.parse(dateString);
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        LocalDate date = LocalDate.of(dateTime.getYear(), dateTime.getMonth(), dateTime.getDayOfMonth());

        return date;
    }
}

@RequestMapping(value = "/savePerson", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> savePerson(@ModelAttribute("person") Person person) 
{
    // a some code to save entity
}

我应该如何使用@JsonDeserialize

最佳答案

这可能符合您的目的:

public class Person {
    @JsonProperty("birthday")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="MM.dd.yyyy")
    private LocalDate birthday;

    // other fields, getter and setter, etc.
}

关于java - @JsonDeserialize 注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36633405/

相关文章:

java - arraylist isEmpty() 疑惑与疑问

java - Spring模型验证错误

java - 使用 parallelStream().reduce() 时的错误结果

java - Spark 流式传输和模拟 hdfs

java - Statement.setFetchSize(nSize) 方法在 SQL Server JDBC 驱动程序中的真正作用是什么?

java - Spring框架和Quartz调度器

spring-mvc - Spring MVC 与 Spring Security 的集成测试

lambda - 如何在 JAVA8 中使用 Lambda 将 List<T> 转换为 List<Map<K,V>>

java - 使用 Gson 映射可选值

java - 一个 Java applet 中的两个线程最佳实践