to deserialize JSON in RealmObject use the following
let's say you have a class definition like this
@RealmClass public class Foo extends RealmObject{ private String name; public void setName(String name){ this.name = name} public String getName(){ return this.name} }
and json payload as follows:
String json = "{\"name\":\"bar\"}"; Foo fooObject= realm.createObjectFromJson(Foo.class, json); //or String jsonArray = "[{\"name\":\"bar\"},{\"name\":\"baz\"}]"; RealmList<Foo> fooObjects = realm.createAllFromJson(Foo.class, jsonArray);
However, the opposite is not supported in the realm-core. so this is how i get around this. I tried to use GSON , but in the end I wrote too many codes that I myself did not understand, so I implemented my own adapter, like this one. The problem is that RealmObjects are not the "kingdom" of java.lang.Object .
create an adapter that takes an instance of your realm object and returns its JSON representation.
Example.
public class RealmJsonAdapter{ public JSONObject toJson(Foo foo){ JSONObject obj = new JSONObject(); obj.putString("name",foo.getName());
you can now use this adapter in your classes to serialize RealmObject to JSON . perhaps you will make the adapter an interface so that you allow subscribers (maybe you yourself) to pass on the adapter you want to use. you can call adapter.toJSON(realmObjectInstance) . and get the implementation of JSONObject in the end you only care about JSON, not RealmObject.
Note This solution is slightly characterized. RealmObjects are now real Java objects, so you can use it with GSON without any problems. Just make sure you are using version 0.89 or later and everything will work fine.
source share