【问题标题】:Serialization of Custom Class Using GSON使用 GSON 序列化自定义类
【发布时间】:2017-07-09 06:55:51
【问题描述】:

我列出了我尝试使用 json 序列化的自定义类的对象,但序列化后的值为 0,而不是存储在列表中的实际值。

我的自定义类

public class CustomClass extends RealmObject {

@Expose()
@SerializedName("startID")
private int startMessageID;

@Expose()
@SerializedName("endID")
private int endMessageID;

@Expose(serialize = false)
private boolean syncing = false;

}

以下是我用来序列化列表的内容。

 GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    Gson gson = builder.create();
    Type listType = new TypeToken<List<CustomClass >>() {
    }.getType();

    Log.i("Json", gson.toJson(syncModelList, listType));

上面的代码产生一个输出

[{"endID":0,"startID":0},{"endID":0,"startID":0}]

结构正确但我的值丢失了,我在序列化之前检查了值,它们是正确的并且存在。

【问题讨论】:

标签: android json serialization gson


【解决方案1】:

这是因为 Gson 无法序列化托管的 Realm 对象。您需要先将其转换为非托管对象,如下所示:

new Gson().toJson(realm.copyFromRealm(managedModel));

查看这个答案以获得完整的解释Android: Realm + Retrofit 2 + Gson

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2013-09-09
    • 2013-03-09
    相关资源
    最近更新 更多