使用GSON序列化自定义类

时间:2017-07-09 06:55:52

标签: android json serialization gson

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

MyCustom Class

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}]

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

1 个答案:

答案 0 :(得分:1)

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

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

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