Gson 中是否有 JsonFormat 的类似物?

Is there any analogue of JsonFormat in Gson?

我的问题真的很小:

比fastrxml.jackson更喜欢Gson。我希望在 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)

将生成 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;
}

要将 JSON 反序列化为 POJO Gson 使用 com.google.gson.internal.bind.ReflectiveTypeAdapterFactory class 标记为 final。要处理额外的注释,您必须实现类似的东西并创建新的注释并在反序列化逻辑中处理它。现在,您可以实现您的自定义 com.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'}