我有一个由GSON库生成的JSON字符串,它看起来像:
{ "id": 10, "articleNumber": 5009, "processDate": { "year": 2021, "month": 1, "day": 1 }, "price": 1.22}
{
"id": 10,
"articleNumber": 5009,
"processDate": {
"year": 2021,
"month": 1,
"day": 1
},
"price": 1.22
}
我想使用Jackson反序列化上面的JSON。但是由于processDate字段在JSON中的格式,它在processDate字段处失败。如何使用一些自定义的反序列化器解析上面的JSON字符串?
processDate
guykilcj1#
似乎您不情愿地得到了Jackson内置的LocalDateDeserializer来解析您的日期。
LocalDateDeserializer
"2021-1-1"
[2021, 1, 1]
18627
但不幸的是不是你的类对象格式
{ "year": 2021, "month" :1, "day": 1 }
因此,您需要为LocalDate编写自己的反序列化器。这并不困难。
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 = node.get("year").intValue(); int month = node.get("month").intValue(); int day = node.get("day").intValue(); return LocalDate.of(year, month, day); } catch (Exception e) { throw JsonMappingException.from(parser, node.toString(), e); } }}
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 = node.get("year").intValue();
int month = node.get("month").intValue();
int day = 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)}
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)
wtlkbnrh2#
我对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; }}
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;
2条答案
按热度按时间guykilcj1#
似乎您不情愿地得到了Jackson内置的
LocalDateDeserializer
来解析您的日期。"2021-1-1"
个[2021, 1, 1]
18627
但不幸的是不是你的类对象格式
{ "year": 2021, "month" :1, "day": 1 }
因此,您需要为
LocalDate
编写自己的反序列化器。这并不困难。然后,在Java类中,您需要告诉Jackson,您希望其
processDate
属性由您自己的LocalDateDeserializer
反序列化。wtlkbnrh2#
我对java不是很了解,只是做了一个像这样的自定义类型。下面只是创建了一个像这样的自定义结构: