@JsonDeserialize 注释不起作用

@JsonDeserialize annotation do not working

我遇到了 @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.
}

log4j 的设置对我帮助很大:"log4j.category.org.springframework=ALL"