首页 > 解决方案 > Gson 中是否有类似 JsonFormat 的内容?

问题描述

我的问题真的很小:

我更喜欢 Gson,而不是 fastrxml.jackson。我想在 Gson 中看到的一个可能的功能是:

//some code
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date endDate;
//some code

我发现在 Gson 中做同样事情的唯一方法是:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();

我认为注释比初始化更容易理解。有什么方法可以注释或制作一些属性,以便代码

gson.fromJson("\"{\\\"Id\\\": 703,\\\"StartDate\\\": \\\"2019-10-01T00:00:00\\\"," +
    " \\\"EndDate\\\": \\\"2019-10-25T00:00:00\\\",\\\"Title\\\": \\\"exmample title\\\"}\"",
  MyObj.class)

将产生 MyObj 类的对象:

public class MyObj{
    @SerializedName("Id")
    private Long id;
    @SerializedName("StartDate")
    //analogue of JsonFormat????
    private Date startDate;
    @SerializedName("EndDate")
    //analogue of JsonFormat????
    private Date endDate;
    @SerializedName("Title")
    private String title;
}

标签: javajsongson

解决方案


反序列化为使用标记为的JSON类。要处理额外的注释,您必须实现类似的东西并创建新的注释并在反序列化逻辑中处理它。现在,您可以实现允许解析给定日期的自定义。POJO Gsoncom.google.gson.internal.bind.ReflectiveTypeAdapterFactoryfinalcom.google.gson.JsonDeserializer

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class GsonApp {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().create();
        MyObj myObj = gson.fromJson(
                "{\"Id\": 703,\"StartDate\": \"2019-10-01T00:00:00\",\"EndDate\": \"2019-10-25T00:00:00\",\"Title\": \"exmample title\"}",
                MyObj.class);
        System.out.println(myObj);
    }
}

class IsoDateTimeJsonDeserializer implements JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        LocalDateTime localDateTime = LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ISO_DATE_TIME);

        return Date.from(localDateTime.atZone(ZoneOffset.systemDefault()).toInstant());
    }
}

class MyObj {

    @SerializedName("Id")
    private Long id;

    @SerializedName("StartDate")
    @JsonAdapter(IsoDateTimeJsonDeserializer.class)
    private Date startDate;

    @SerializedName("EndDate")
    @JsonAdapter(IsoDateTimeJsonDeserializer.class)
    private Date endDate;

    @SerializedName("Title")
    private String title;

    // getters, setters, toString
}

上面的代码打印:

MyObj{id=703, startDate=Tue Oct 01 00:00:00 CEST 2019, endDate=Fri Oct 25 00:00:00 CEST 2019, title='exmample title'}

推荐阅读