我有一個由 GSON 庫生成的 JSON 字串,它看起來像:
{
"id": 10,
"articleNumber": 5009,
"processDate": {
"year": 2021,
"month": 1,
"day": 1
},
"price": 1.22
}
我想使用 Jackson 反序列化上述 JSON。但processDate由于processDateJSON 中欄位的格式,它在欄位中失敗。
如何使用一些自定義反序列化器決議上述 JSON 字串?
uj5u.com熱心網友回復:
看來你不情愿地得到了杰克遜的內置
LocalDateDeserializer決議你的約會。此解串器支持多種 JSON 日期格式(字串、整數陣列、紀元日計數)
"2021-1-1"[2021, 1, 1]18627
但不幸的是不是你的類物件格式
{ "year": 2021, "month" :1, "day": 1 }
因此,您需要為LocalDate. 這并不難。
public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = parser.getCodec().readTree(parser);
try {
int year = ((IntNode) node.get("year")).intValue();
int month = ((IntNode) node.get("month")).intValue();
int day = ((IntNode) node.get("day")).intValue();
return LocalDate.of(year, month, day);
} catch (Exception e) {
throw JsonMappingException.from(parser, node.toString(), e);
}
}
}
然后,在您的 Java 類中,您需要告訴 Jackson,您希望它的processDate屬性由您自己的LocalDateDeserializer.
public class Root {
private int id;
private int articleNumber;
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate processDate;
private double price;
// getters and setters (omitted here for brevity)
}
uj5u.com熱心網友回復:
我不太了解java,只需制作一個這樣的自定義型別。下面只是創建一個自定義結構,如:
inline class processDate {
int year,
int month,
int day,
public Date getDate(){
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date date = formatter.parse(this.day "-" this.month "-" this.year);
return date;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326690.html
上一篇:WinSCP-未知命令和'.log'未被識別為內部或外部命令
下一篇:用通配符過濾陣列行
