简体   繁体   中英

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 :

{ "birthday": 1 }

should not be accepted.

I tried

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private LocalDate birthday;

but still accept numbers.

First create a class custom localDate deserializer

public class LocalDateDserializer extends 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM