How can I serialize RealmObject for JSON to Realm for Java?

I am using DB for my application and I am trying to "connect" it to my REST interface. Data comes in as JSON and with new JSON support (starting with Realm 0.76). I can throw JSON on my Realm.createObjectFromJson(MyType.class, jsonString) and create the corresponding arguments and RealmLists.

But how can I do the opposite? That is, take RealmObject and serialize it to JSON? It must also serialize any RealmList object inside this object.

+6
source share
5 answers

Kingdom Christian is here. Realm for Android does not currently have such methods, although the underlying database actually supports JSON serialization, so at the moment you will have to either manually or use a third-party tool such as GSON (caveat, I have not tested this script yet).

+3
source

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()); //if you have more fields you continue return obj; } } 

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.

+7
source

Just all you have to do is:

 Gson gson = //... obtain your Gson 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); } 
+5
source

Below you will learn how to do this with the GSON library.

Suppose we have the following json response from the server:

 {   "data": [      {         "id": "1",         "name": "John",         "surname": "Doe"      }   ] } 

For this Json object, we create a helper class with the appropriate properties

  public class JsonHelperClass { String id; String name; String surname; public JsonHelperClass() { } public JsonHelperClass(String id, String name, String surname) { this.id = id; this.name = name; this.surname = surname; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } } 

Now in the next jsonReply is a line containing the response from the server

  JSONArray jsonArray = new HttpManager().getJsonArrayFromReply(jsonReply); if(jsonArray == null || jsonArray.length <0){ return; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = null; try { json = (JSONObject) array.get(i); } catch (JSONException e) { return null; } Gson gson = new Gson(); JsonHelperClass helperClass = gson.fromJson(json.toString(), JsonHelperClass.class); createRealmObject(helperClass); } public void createRealmObject(JsonHelperClass helperClass){ Realm realm = Realm.getInstance(context); realm.beginTransaction(); RealmDataObject obj = realm.createObject(RealmDataObject.class); obj.setId(helperClass.getId()); obj.setName(helperClass.getName()); obj.setSurname(helperClass.getSurname()); realm.commitTransaction(); } public JSONArray getJsonArrayFromReply(String reply){ JSONArray array = null; try { JSONObject jsonResp = new JSONObject(reply); array = jsonResp.getJSONArray("data"); } catch (JSONException e) { return null; } return array; } 

And the realm data object

  public class RealmDataObject extends RealmObject { private String id; private String name; private String surname; public RealmDataObject() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } } 
+1
source

Try

  private JSONArray convertRealmintoJSONArray(Activity context){ try { RealmResults<ModelMyCart> results = RealmControllerMyCart.with(context).getBooks(); JSONArray jsonArray = new JSONArray(); for (ModelMyCart myCart : results ) { JSONObject object = new JSONObject(); object.put(Constants.PRODUCT_ID, myCart.getId()); object.put(Constants.PRODUCT_TITLE, myCart.getProduct_title()); object.put(Constants.PRODUCT_SIZE, myCart.getProduct_size()); object.put(Constants.PRODUCT_SELLINGFEE, myCart.getProduct_sellingfee()); object.put(Constants.PRODUCT_SELLINGFEE, myCart.getShipping_price()); object.put(Constants.PRODUCT_IMAGE, myCart.getProduct_image()); object.put(Constants.PRODUCT_BRAND, myCart.getProduct_brand()); object.put(Constants.PRODUCT_CATEGORY_ID, myCart.getProduct_category_id()); object.put(Constants.PRODUCT_CATEGORY_NAME, myCart.getProduct_category_name()); object.put(Constants.PRODUCT_COLOR, myCart.getProduct_color()); object.put(Constants.PRODUCT_COLORTYPE, myCart.getProduct_colortype()); object.put(Constants.PRODUCT_CONDITION, myCart.getProduct_condition()); object.put(Constants.PRODUCT_CREATED_DATE, myCart.getProduct_created_date()); object.put(Constants.PRODUCT_MYSALEPRICE, myCart.getProduct_mysaleprice()); object.put(Constants.PRODUCT_ORIGINALPRICE, myCart.getProduct_originalprice()); object.put(Constants.PRODUCT_POTENTIALEARNINGS, myCart.getProduct_potentialearnings()); object.put(Constants.PRODUCT_SHIPPINGCHARGES, myCart.getProduct_shippingcharges()); object.put(Constants.USER_ID, myCart.getUser_id()); object.put(Constants.USER_UNAME, myCart.getUser_uname()); jsonArray.put(object); } Log.e("Converted",""+jsonArray); return jsonArray; }catch (Exception e){ } return null; } 
0
source

Source: https://habr.com/ru/post/980870/


All Articles