Ich habe das Problem, wenn eine @JsonDeserialize
Annotation nicht funktioniert. Ich habe 400 Bad Request
HTTP-Code-Antwort, wenn der Wert des Geburtstags von Client enthält "12.06.1999", in Beispiel. Es ist ein sehr seltsames Verhalten für mich, weil @JsonSerialize
Annotation gut funktioniert! Aber wenn ich @DateTimeFormat
Annotation anstelle von @JsonDeserialize
dann alles funktioniert.@JsonDeserialize Annotation funktioniert nicht
Ich benutze Java 8 und es ist mein Code:
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
}
Wie soll ich @JsonDeserialize
benutzen?
erinnern Sie sich, wie hast du es lösen? – deadManN