为什么这个空值没有被序列化?

时间:2018-04-20 19:54:19

标签: java gson retrofit2

所以我有一个我们正在序列化为gson的对象,end值为null。但是,不是在json对象中显示为null,而是{j}对象中缺少end的整个键值对。

这是对象的POJO。

public static class History {
   @NonNull
   public final String areaId;
   @NonNull
   public final String userId;
   public final long start;
   @Nullable
   public final Long end;
   public History(@NonNull String areaId, @NonNull String userId, long start, @Nullable Long end) {
        this.areaId = areaId;
        this.userId = userId;
        this.start = start;
        this.end = end;
   }
}

这是gson Builder

GsonBuilder()
    .serializeNulls()
    .registerTypeAdapter(Date.class, new DateFormatter())
    .setFieldNamingStrategy(fieldNamingStrategy)
    .create();

这就是json实际上的样子

areaUserHistories": {
         "aff824c6-df4f-49b4-8dea-6c204cb7bb16": {
         "areaId": "ca5f5e6f-77eb-4859-a2ad-c3b249e53493",
         "start": 1524178713,
         "userId": "911705136"
        }
    } 

这应该是它的样子,

areaUserHistories": {
         "aff824c6-df4f-49b4-8dea-6c204cb7bb16": {
         "areaId": "ca5f5e6f-77eb-4859-a2ad-c3b249e53493",
         "start": 1524178713,
         "end": null
         "userId": "911705136"
        }
    },

EIDT 1

所以我正在尝试,我将这行代码添加到GsonBuilder,.setLongSerializationPolicy(LongSerializationPolicy.STRING)

以便Gson Builder现在将Long值转换为String。这导致正确添加end=null值。不幸的是,价值需要很长。

1 个答案:

答案 0 :(得分:-3)

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.serializeNulls();

Gson gson = gsonBuilder.create();

String jsonString = gson.toJson(object);