Gson在转换时从日期中删除时间戳

1hdlvixo  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(140)

我正在使用Gson将JSON字符串转换为POJO类。在Pojo中,属性是java.util.Date类型。当gson将Json字符串Map到Pojo对象时,它正在删除时间戳。

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'").create();
ClassBaseModel baseModel = gson.fromJson(request, ClassBaseModel.class);

Attribute Original Value in String Json is - "orderDate": "2021-12-01T07:16:31Z"
After It is converted into POJO - 2021-12-01
Expected is - 2021-12-01T07:16:31Z

我不知道我做错了什么。有人能指出吗?

9wbgstp7

9wbgstp71#

反序列化时,必须使用registerTypeAdapter在gson中注册反序列化器类型
这是我如何尝试这样做,也
请求类:

class OrderInfoRequest {
    String orderDate;

    public OrderInfoRequest(String orderDate) {
        this.orderDate = orderDate;
    }
}

主Map器类

class OrderInfo {
    OffsetDateTime orderDate;

    public OffsetDateTime getOrderDate() {
        return orderDate;
    }

    public void setOrderDate(OffsetDateTime orderDate) {
        this.orderDate = orderDate;
    }

    @Override
    public String toString() {
        return "OrderInfo{" +
                "orderDate=" + orderDate +
                '}';
    }
}

样本代码

public class DateMain {
        public static void main(String[] args) {
            OrderInfoRequest orderInfoRequest = new OrderInfoRequest("2021-12-01T07:16:31Z");
            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(OffsetDateTime.class, (JsonDeserializer<OffsetDateTime>) (json, typeOfT, context) -> OffsetDateTime.parse(json.getAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                    .create();

            String requestJson = gson.toJson(orderInfoRequest);
            System.out.println("Request json");
            System.out.println(requestJson);
            OrderInfo orderInfo = gson.fromJson(requestJson, OrderInfo.class);
            System.out.println("After parsing pojo");
            System.out.println(orderInfo);

            System.out.println("printing full date: " + orderInfo.orderDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd, hh:mm")));

        }
    }

另外,正如@Jens所告诉的,如果你还没有使用java.util.Date类,从今天开始就不要使用。

相关问题