I am implementing a DB for my Application and I am trying "connect" it to my REST interface. The data comes in as JSON and with the new JSON-Support (as of Realm 0.76) I can throw the JSON at my Realm.createObjectFromJson(MyType.class, jsonString)
and it creates the appropiate obejcts and RealmLists.
But how can I do the opposite? That is, take a RealmObject and serialize it to JSON? It also should serialize any RealmList inside that object.
Try this
Christian from Realm here. Realm for Android currently doesn't have any such methods, although the core database actually supports JSON serialisation, so for now you would either have to do it manually or use a 3rd party tool like GSON (caveat, I havn't tested that scenario yet).
Following is how you would do that with GSON library.
Suppose we have the following json reply from the server :
For this Json object we create a helper class with corresponding properties
Now in the following jsonReply is the string containing reply from server
And the Realm Data Object
Simply, all you need to do is:
to deserialize JSON into RealmObject use on of the following
say you have a class definition like this
and a json payload like this:
However the reverse is not natively supported in realm-core. so this is how i work around it. i attempted to use GSON, but ended up writing too many codes that i myself did not understand so i implemented my own adapter like this.The problem is RealmObjects are not 'realm'
java.lang.Object
.create an adapter that takes instance of your realm object and return its JSON representation.
example.
you can now use this adapter in your classes to serialize you
RealmObject
to JSON. prefferably you would make the adapter an interface so that you let callers (might be you yourself) pass you the adapter the want to use. you can then call say,adapter.toJSON(realmObjectInstance)
. and get your JSONObject implementation after all you care only about the JSON and not the RealmObject.NOTE This solution is a bit oudated. RealmObjects are now real java objects so you should be able to use it with GSON with no problems. Just make sure you are using version 0.89 or later and everything will work fine.