更新时间:2022-11-06 21:49:40
您可以编写自定义解串器为您的班级设置了默认值,以防出现问题.像这样:
You could write a custom deserializer for your class where you set a default value in case something goes wrong. Something like:
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();
}
}
}
然后在您的课堂上,您可以执行以下操作:
Then on your class you could do something like:
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)
.
You could also add @JsonIgnoreProperties(ignoreUnknown = true)
over your class if you know that its value is not necessary always.