【问题标题】:How to deserialize JSON containing LocalDate field generated by GSON library如何反序列化包含 GSON 库生成的 LocalDate 字段的 JSON
【发布时间】:2021-12-06 08:52:59
【问题描述】:

我有一个由 GSON 库生成的 JSON 字符串,它看起来像:

{
    "id": 10,
    "articleNumber": 5009,
    "processDate": {
      "year": 2021,
      "month": 1,
      "day": 1
    },
    "price": 1.22
}

我想使用 Jackson 来反序列化上述 JSON。但由于 processDate 字段在 JSON 中的格式,它在 processDate 字段中失败。

如何使用一些自定义的反序列化器来解析上面的 JSON 字符串?

【问题讨论】:

  • @ℛɑƒæĿᴿᴹᴿ 日期字段不是对象格式。就像 "processDate" : "2021-01-01"
  • 为什么不简单地将其设置为 ISO 8601 格式,以便 每个 您的组件(当然至少 Java 8 Time API 知道)可以意识到这一点?首先将LocalDate-to-String 序列化程序添加到Gson

标签: json jackson gson deserialization localdate


【解决方案1】:

看来你不情愿地得到了杰克逊的内置 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 = 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 课程中,您需要告诉杰克逊, 你希望它的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)
}

【讨论】:

    【解决方案2】:

    我不太了解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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 1970-01-01
      • 2014-10-04
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多