POJO使用自定义反序列化器与Gson映射

问题描述 投票:0回答:1

我有一个简单的POJO类,看起来像这样:

public class EventPOJO {

    public EventPOJO() {
    }


    public String id, title;
    // Looking for an annotation here
    public Timestamp startDate, endDate;
}

我有一个EventPOJO实例,需要将此实例反序列化为Map对象。

Gson gson = new GsonBuilder().create();
String json = gson.toJson(eventPOJO)
Map<String,Object> result = new Gson().fromJson(json, Map.class);

我需要result映射以包含类型为"startDate" Timestamp。(com.google.firebase.Timestamp)

然而,result包含key "startDate",类型LinkedTreeMapvalue包含纳秒和秒。

我尝试创建自定义反序列化器

 GsonBuilder gsonBuilder = new GsonBuilder();
 gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer());
 Gson gson = gsonBuilder.create();
 String json = gson.toJson(eventPOJO);
 Map<String,Object> result = gson.fromJson(json, Map.class);

TimestampDeserializer.java

public class TimestampDeserializer implements JsonDeserializer<Timestamp>
{
    @Override
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        //not sure how to retrieve the seconds from the parameters
        return new Timestamp(999999999, 0);
    }
}

反序列化甚至都不会被调用,而且我仍在获取没有Timestamp对象的Map。

java gson
1个回答
0
投票

这是firebase.Timestamp反序列化的方式。如果您需要反序列化实际时间,则可以采取解决方法。将您的startDate,endDate设置为transient,这样它们就不会出现在json字符串中,然后为它们添加辅助字段和初始化程序:

public class EventPOJO {

    public EventPOJO() {
    }

    public String id, title;
    transient public Timestamp startDate, endDate;
    public long startSeconds;
    public int  startNanoSeconds;
    public long endSeconds;
    public int  endNanoSeconds;

    public void initFields() {
        startSeconds = startDate.getSeconds();
        startNanoSeconds = startDate.getNanoSeconds();
        endSeconds = endDate.getSeconds();
        endNanoSeconds = endDate.getNanoSeconds();
    }
}

然后在initFields()之前调用toJson(eventPOJO)

    eventPOJO.initFields(); 
    String json = gson.toJson(eventPOJO);

您应该得到类似的东西

{id=123, startSeconds=47245722.0, startNanoSeconds=436.0, endSeconds=47245726.0, endNanoSeconds=452.0}
© www.soinside.com 2019 - 2024. All rights reserved.