当@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/