[英]How i can force JSON dates to not accept integer in java
How i can force JSON date with Java to use a particular pattern and don't accept Integers, for example :我如何使用 Java 强制 JSON 日期使用特定模式并且不接受整数,例如:
{ "birthday": 1 } {“生日”:1}
should not be accepted.不应该被接受。
I tried我试过
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private LocalDate birthday; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private LocalDate 生日;
but still accept numbers.但仍然接受数字。
First create a class custom localDate deserializer首先创建一个类自定义localDate反序列化器
public class LocalDateDserializer extends StdDeserializer {公共类 LocalDateDserializer 扩展 StdDeserializer {
private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
public LocalDateDserializer() {
this(null);
}
public LocalDateDserializer(final Class<?> vc) {
super(vc);
}
@Override
public LocalDate deserialize(final JsonParser jsonparser, final DeserializationContext context)
throws IOException, JsonProcessingException {
final String date = jsonparser.getText();
try {
return formatter.parse(date).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
} catch (final ParseException e) {
throw new RuntimeException(e);
}
}
} }
Use the annotation @JsonDeserialize(using = LocalDateDserializer.class) private LocalDate birthday;使用注解@JsonDeserialize(using = LocalDateDserializer.class) private LocalDatebirthday;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.