2 回答

TA貢獻1893條經驗 獲得超10個贊
您需要一個帶有所有參數的構造函數:
public SampleRequest(String fromDate, String toDate) {
this.fromDate = fromDate;
this.toDate = toDate;
}
或使用@AllArgsConstructor或@Data來自龍目島。

TA貢獻1839條經驗 獲得超15個贊
您需要編寫自定義反序列化器,因為它無法將字符串(fromDate 和 toDate)解析為 Date
{ "fromDate":"2019-03-09", "toDate":"2019-03-10" }
這個鏈接有一個教程開始使用自定義反序列化器https://www.baeldung.com/jackson-deserialization
反序列化器可以這樣寫。
public class CustomDateDeserializer extends StdDeserializer<Date> {
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}}
您可以像這樣在 Class 本身注冊反序列化器。
@JsonDeserialize(using = ItemDeserializer.class)
public class Item { ...}
或者您可以像這樣手動注冊自定義反序列化器
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Item.class, new ItemDeserializer());
mapper.registerModule(module);
添加回答
舉報