Gson Serializer for a given class if in another specific class

Gson Serializer for a given class if in another specific class

我正在尝试序列化(使用 Gson)一个 POJO 并对其单个字段进行特殊处理。

是否有可能比编写实现 JsonSerializer 的适配器并使其 serialize() 方法复制除接受特殊处理的特定字段之外的每个字段更简单的方法?

是否可以在我的 POJO 中使用注释来实现它?

我也不能只编写特定字段类型的适配器,因为它是 java.util.Date,我不希望每个序列化日期都接受这种处理。


这是一个例子:

public class Pojo {

    @SerializedName("effectiveDate")
    private final Date mDate;

    @SerializedName("status")
    private final Status mStatus; // <-- The field needing specific serialization

    @SerializedName("details")
    private final String mDetails;

    // other fields

    // methods
}

我想避免这样编码适配器:

public class PojoAdapter implements JsonSerializer<Pojo> {

    @Override
    public JsonElement serialize(final Pojo src, final Type typeOfSrc, final JsonSerializationContext context) {
        final JsonObject jsonPojo = new JsonObject();
        jsonDeployment.add("effectiveDate", /* special treatment */);        
        jsonDeployment.add("status", src.getStatus());
        jsonDeployment.add("details", src.getDetails());
        // other fields setting
        return jsonPojo;
    }
}

您可以为 Date class 实现自定义 com.google.gson.JsonSerializer 并为给定字段使用 com.google.gson.annotations.JsonAdapte 注释来注册它。请参阅以下示例:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;

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

public class GsonApp {

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        System.out.println(gson.toJson(new DatesPojo(new Date())));
    }

}

class CustomDateJsonSerializer implements JsonSerializer<Date> {
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        String format = src.toInstant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ISO_TIME);
        return new JsonPrimitive(format + " ISO TIME");
    }
}

class DatesPojo {

    @JsonAdapter(CustomDateJsonSerializer.class)
    @SerializedName("customDate")
    private final Date mDate0;

    @SerializedName("effectiveDate")
    private final Date mDate1;

    public DatesPojo(Date mDate) {
        this.mDate0 = mDate;
        this.mDate1 = mDate;
    }

    public Date getmDate0() {
        return mDate0;
    }

    public Date getmDate1() {
        return mDate1;
    }
}

以上代码打印:

{
  "customDate": "22:37:21.806+01:00 ISO TIME",
  "effectiveDate": "Jan 22, 2020 10:37:21 PM"
}

我找到了另一个解决方案,它包括让我的 Date 字段实现一个 EffectiveDate 接口,它只是扩展 Date 并为这个单一字段添加一个适配器。