Syed Hassan
Syed Hassan

Reputation: 438

How to convert RealmResult to Json using Gson library

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

Answers (4)

hamil.Dev
hamil.Dev

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

Mike Frolov
Mike Frolov

Reputation: 51

You get StackOverflow becouse of Gson based on reflection but managed object (RealmObjectProxy) have no real fields and fields of parent is nulls 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:

  1. Write your own adapter for every RealmObject childs which will takes data using getters.

  2. Call realm.copyFromRealm(realmObject) before serialisation. It will looks like new Gson().toJson(realm.copyFromRealm(realmObject))

  3. Use library based on 2nd option RealmSupportForGson

Hope it helps

Upvotes: 1

Warrior Within
Warrior Within

Reputation: 49

The easier way is create a List<Dog> with RLMResult<Dog>, and then serialise this List with Gson.

Upvotes: 0

Christian Melchior
Christian Melchior

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

Related Questions