Search code examples
jsongsonrealmrealm-list

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.


Solution

  • 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