Reputation: 438
In this question How can I serialize a RealmObject to JSON in Realm for Java? The realm representative said that one can serialize realm object through GSON. Can you please explain it how? I tried this.
RealmResults<Dog> myDogs=realm.where(Dog.class).findAll();
new Gson().toJson(myDogs);
But StackOverflowError occurred.
Upvotes: 2
Views: 1378
Reputation: 388
After two days of bug resolve, I found this simple solution:
YourRealmObject realmObj = realm.where(YourRealmObject.class).findFirst();
if(realmObj != null) {
realmObj = realm.copyFromRealm(realmObj); //detach from Realm, copy values to fields
String json = gson.toJson(realmObj);
}
Upvotes: 0
Reputation: 51
You get StackOverflow
becouse of Gson
based on reflection but managed object (RealmObjectProxy
) have no real fields and fields of parent is null
s also some of proxy fields produses recursion in field type recognition of Gson
it happens in $GsonTypes
class.
To serialize RealmObject
you can use one of this options:
Write your own adapter for every RealmObject
childs which will takes data using getters.
Call realm.copyFromRealm(realmObject)
before serialisation. It will looks like new Gson().toJson(realm.copyFromRealm(realmObject))
Use library based on 2nd option RealmSupportForGson
Hope it helps
Upvotes: 1
Reputation: 49
The easier way is create a List<Dog>
with RLMResult<Dog>
, and then serialise this List with Gson.
Upvotes: 0
Reputation: 20126
To make GSON serialization work with Realm you will need to write a custom JsonSerializer for each object that can be serialized and register it as a TypeAdapter.
You can see an example in this gist: https://gist.github.com/cmelchior/ddac8efd018123a1e53a
Upvotes: 1