当@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
?
答案 0 :(得分:0)
这可能符合您的目的:
public class Person {
@JsonProperty("birthday")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="MM.dd.yyyy")
private LocalDate birthday;
// other fields, getter and setter, etc.
}
答案 1 :(得分:0)
log4j的设置对我帮助很大:&#34; log4j.category.org.springframework = ALL&#34;