你可以写一个习惯
deserializer
为您的类设置默认值,以防出错。类似于:
public class MyJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
return new Date();
}
}
}
然后在你的课上你可以做如下的事情:
class MyClass {
//...Fields
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
@JsonDeserialize(using = MyJsonDateDeserializer.class)
private Date date;
//...Fields
}
您还可以添加
@JsonIgnoreProperties(ignoreUnknown = true)