0

I list of objects of a custom class which i am trying to serialize using json but the values once serialized are 0 and not the actual values that are stored in the list.

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;

}

The following is what i use to serialize the list.

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

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

The above code produces an output of

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

The structure is correct but my values are lost,i have checked the values before serialization and they are correct and exist.

Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90

1 Answers1

1

It's because Gson can't serialize a managed Realm object. You need to convert it to an unmanaged object first, like this:

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

Have a look at this answer for a full explanation Android: Realm + Retrofit 2 + Gson

bobtune
  • 1,316
  • 1
  • 9
  • 11