How Can I Serialize A Realmobject To Json In Realm For Java?
Solution 1:
Simply, all you need to do is:
Gsongson=//... obtain your GsonYourRealmObjectrealmObj= realm.where(YourRealmObject.class).findFirst();
if(realmObj != null) {
realmObj = realm.copyFromRealm(realmObj); //detach from Realm, copy values to fieldsStringjson= gson.toJson(realmObj);
}
Solution 2:
to deserialize JSON into RealmObject use on of the following
say you have a class definition like this
@RealmClasspublicclassFooextendsRealmObject{
privateString name;
publicvoidsetName(String name){ this.name = name}
publicStringgetName(){ returnthis.name}
}
and a json payload like this:
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 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.
publicclassRealmJsonAdapter{
publicJSONObjecttoJson(Foo foo){
JSONObject obj = newJSONObject();
obj.putString("name",foo.getName());
//if you have more fields you continuereturn obj;
}
}
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.
Solution 3:
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).
Solution 4:
Following is how you would do that with GSON library.
Suppose we have the following json reply from the server :
{
"data":[
{
"id":"1",
"name":"John",
"surname":"Doe"
}
]}
For this Json object we create a helper class with corresponding properties
publicclassJsonHelperClass {
String id;
String name;
String surname;
publicJsonHelperClass() {
}
publicJsonHelperClass(String id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
publicStringgetId() {
return id;
}
publicvoidsetId(String id) {
this.id = id;
}
publicStringgetName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
publicStringgetSurname() {
return surname;
}
publicvoidsetSurname(String surname) {
this.surname = surname;
}
}
Now in the following jsonReply is the string containing reply from server
JSONArray jsonArray = newHttpManager().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) {
returnnull;
}
Gson gson = newGson();
JsonHelperClass helperClass = gson.fromJson(json.toString(), JsonHelperClass.class);
createRealmObject(helperClass);
}
publicvoidcreateRealmObject(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();
}
publicJSONArraygetJsonArrayFromReply(String reply){
JSONArray array = null;
try {
JSONObject jsonResp = newJSONObject(reply);
array = jsonResp.getJSONArray("data");
} catch (JSONException e) {
returnnull;
}
return array;
}
And the Realm Data Object
publicclassRealmDataObjectextendsRealmObject {
privateString id;
privateString name;
privateString surname;
publicRealmDataObject() {
}
publicStringgetName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
publicStringgetId() {
return id;
}
publicvoidsetId(String id) {
this.id = id;
}
publicStringgetSurname() {
return surname;
}
publicvoidsetSurname(String surname) {
this.surname = surname;
}
}
Solution 5:
Try this
privateJSONArrayconvertRealmintoJSONArray(Activity context){
try {
RealmResults<ModelMyCart> results = RealmControllerMyCart.with(context).getBooks();
JSONArray jsonArray = newJSONArray();
for (ModelMyCart myCart : results
) {
JSONObjectobject = newJSONObject();
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){
}
returnnull;
}
Post a Comment for "How Can I Serialize A Realmobject To Json In Realm For Java?"