// GSON can parse the data. | |
// | |
// Deserialization: | |
// Note there is a bug in GSON 2.3.1 that can cause it to StackOverflow when working with RealmObjects. | |
// To work around this, use the ExclusionStrategy below or downgrade to 1.7.1 | |
// See more here: https://code.google.com/p/google-gson/issues/detail?id=440 | |
// | |
// Serialization: | |
// <Type>RealmProxy objects are created by the Realm annotation processor. They are used to control | |
// access to the actual data instead of storing them in fields and it is therefore them we need to register a | |
// TypeAdapter for. | |
Gson gson = new GsonBuilder() | |
.setExclusionStrategies(new ExclusionStrategy() { | |
@Override | |
public boolean shouldSkipField(FieldAttributes f) { | |
return f.getDeclaringClass().equals(RealmObject.class); | |
} | |
@Override | |
public boolean shouldSkipClass(Class<?> clazz) { | |
return false; | |
} | |
}) | |
.registerTypeAdapter(Class.forName("io.realm.PersonRealmProxy"), new PersonSerializer()) | |
.registerTypeAdapter(Class.forName("io.realm.DogRealmProxy"), new DogSerializer()) | |
.create(); | |
// Serialize a Realm object to a JSON string | |
String json = gson.toJson(realm.where(Person.class).findFirst()); |
package io.realm.examples; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonSerializationContext; | |
import com.google.gson.JsonSerializer; | |
import java.lang.reflect.Type; | |
import io.realm.examples.realmgridview.Dog; | |
public class DogSerializer implements JsonSerializer<Dog> { | |
@Override | |
public JsonElement serialize(Dog src, Type typeOfSrc, JsonSerializationContext context) { | |
final JsonObject jsonObject = new JsonObject(); | |
jsonObject.addProperty("name", src.getName()); | |
return jsonObject; | |
} | |
} |
package io.realm.example; | |
import io.realm.RealmList; | |
import io.realm.RealmObject; | |
public class Person extends RealmObject { | |
private String name; | |
private int age; | |
private Dog favoriteDog; | |
private RealmList<Dog> dogs; | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public int getAge() { | |
return age; | |
} | |
public void setAge(int age) { | |
this.age = age; | |
} | |
public Dog getFavoriteDog() { | |
return favoriteDog; | |
} | |
public void setFavoriteDog(Dog favoriteDog) { | |
this.favoriteDog = favoriteDog; | |
} | |
public RealmList<Dog> getDogs() { | |
return dogs; | |
} | |
public void setDogs(RealmList<Dog> dogs) { | |
this.dogs = dogs; | |
} | |
} |
package io.realm.example; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonSerializationContext; | |
import com.google.gson.JsonSerializer; | |
import java.lang.reflect.Type; | |
public class PersonSerializer implements JsonSerializer<Person> { | |
@Override | |
public JsonElement serialize(Person src, Type typeOfSrc, JsonSerializationContext context) { | |
final JsonObject jsonObject = new JsonObject(); | |
jsonObject.addProperty("name", src.getName()); | |
jsonObject.addProperty("age", src.getAge()); | |
jsonObject.add("favoriteDog", context.serialize(src.getFavoriteDog())); | |
jsonObject.add("dogs", context.serialize(src.getDogs())); | |
return jsonObject; | |
} | |
} |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
jiahaoliuliu
commented
Nov 22, 2015
Hi:
Source: |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
AlbertVilaCalvo
Nov 26, 2015
I had to do more work than what you show here to serialize a RealmList
. The code jsonObject.add("dogs", context.serialize(src.getDogs()));
was not enough (it did not work properly: was setting the fields to columnInfo
, someIndex
...).
To serialize a RealmList
I used this in my JsonSerializer<>
:
JsonArray dogs = new JsonArray();
for (Dog dog : src.getDogs()) {
// Note: it does not work if you don't pass Dog.class
dogs.add(context.serialize(dog, Dog.class));
}
jsonObject.add("dogs", dogs);
AlbertVilaCalvo
commented
Nov 26, 2015
I had to do more work than what you show here to serialize a To serialize a JsonArray dogs = new JsonArray();
for (Dog dog : src.getDogs()) {
// Note: it does not work if you don't pass Dog.class
dogs.add(context.serialize(dog, Dog.class));
}
jsonObject.add("dogs", dogs); |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
jemshit
commented
Dec 3, 2015
|
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
dongseok0
Feb 3, 2016
For RealmList, it can be done like this:
jsonObject.add("dogs", context.serialize(src.getDogs().toArray(), Dog[].class));
dongseok0
commented
Feb 3, 2016
For RealmList, it can be done like this:
|
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
mohammadrafigh
Feb 18, 2016
@jiahaoliuliu it should work. I think you may used that "io.realm.DogRealmProxy" in the above gist but you should replace that part with your package name. Class.forName() helps you to prevent importing unnecessary classes in your class just for getting their class instance. although in my case I need those classes actually in my activity so I imported those and used them like what you did. thanks to you.
mohammadrafigh
commented
Feb 18, 2016
@jiahaoliuliu it should work. I think you may used that "io.realm.DogRealmProxy" in the above gist but you should replace that part with your package name. Class.forName() helps you to prevent importing unnecessary classes in your class just for getting their class instance. although in my case I need those classes actually in my activity so I imported those and used them like what you did. thanks to you. |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
sam33rdhakal
Mar 1, 2016
I have written the script to generate Serializer classes. No need to manually write these dumb classes.
sam33rdhakal
commented
Mar 1, 2016
I have written the script to generate Serializer classes. No need to manually write these dumb classes. |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
Nekromancer
Apr 18, 2016
gsonBuilder.registerTypeAdapter(DogRealmProxy.class, new DogSerializer());
gsonBuilder.registerTypeAdapter(PersonRealmProxy.class, new PersonSerializer())
Works just fine
Nekromancer
commented
Apr 18, 2016
Works just fine |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
zoopolitic
May 31, 2016
For those who still has troubles with serialization:
Your model:
public class User extends RealmObject {
@PrimaryKey
private String id;
private String name;
private String email;
// getters and setters
}
Your UserSerializer:
public class UserSerializer implements JsonSerializer<User> {
@Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", src.getId());
jsonObject.addProperty("email", src.getEmail());
jsonObject.addProperty("name", src.getName());
}
}
Your method where you call e.g. retrofit interface:
...
private UserApi api;
...
@Override
public void updateUser(String name, String info, String photoUrl) {
User user = realm.copyFromRealm(current); // make copy of the model from realm
user.setName(name);
user.setInfo(info);
user.setPhoto(photoUrl);
api.updateUser(user);
...
}
Your Gson configuration:
new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(User.class, new UserSerializer())
.create();
profit.
zoopolitic
commented
May 31, 2016
•
edited
edited
For those who still has troubles with serialization: Your model:
Your UserSerializer:
Your method where you call e.g. retrofit interface:
Your Gson configuration:
profit. |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
ArthurSav
Jun 13, 2016
The more i use realm, the more reasons i keep finding not to use it.
Yes, you don't have to write boilerplate SQL but you introduce new boilerplate and workarounds.
ArthurSav
commented
Jun 13, 2016
The more i use realm, the more reasons i keep finding not to use it. |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
jemshit
Jul 14, 2016
@cmelchior this doesn't work with Realm-1.1.0 and Retrofit2-2.1.0. Not sure if to create issue for realm or retrofit
jemshit
commented
Jul 14, 2016
@cmelchior this doesn't work with Realm-1.1.0 and Retrofit2-2.1.0. Not sure if to create issue for realm or retrofit |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
btech
Aug 21, 2016
@cmelchior also experiencing this issue...
Update:
this is in fact working with realm 1.1.1; exactly as it is demonstrated. i was using my model class when registering the adapter instead of realm's proxy class for the model.
btech
commented
Aug 21, 2016
•
edited
edited
@cmelchior also experiencing this issue... Update: |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
Zhuinden
Aug 30, 2016
@ArthurSav meh, to serialize with GSON, just call gson.toJson(realm.copyFromRealm(realmObject));
Zhuinden
commented
Aug 30, 2016
•
edited
edited
@ArthurSav meh, to serialize with GSON, just call |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
bvisonl
Dec 31, 2016
@ArthurSav I find it incredibly creepy that I was thinking exactly the same thing right before reading your comment.....
bvisonl
commented
Dec 31, 2016
@ArthurSav I find it incredibly creepy that I was thinking exactly the same thing right before reading your comment..... |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
felixeduardo15
Feb 18, 2017
gson.toJson(realm.copyFromRealm(realmObject)); return a JsonObject? How i can do that? @Zhuinden
felixeduardo15
commented
Feb 18, 2017
gson.toJson(realm.copyFromRealm(realmObject)); return a JsonObject? How i can do that? @Zhuinden |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
HsiangLeekwok
Mar 14, 2017
copyFromRealm will return a unmanaged object/objects, so you can use it directly with no realm exception.
gson.toJson(realm.copyFromRealm(realmObject/realmObjects));
is a lazy function but it worked.
HsiangLeekwok
commented
Mar 14, 2017
copyFromRealm will return a unmanaged object/objects, so you can use it directly with no realm exception. |
This comment has been minimized.
Show comment
Hide comment
This comment has been minimized.
Show comment Hide comment
midoalone
Sep 30, 2017
I am using this and it actually works with me:
Gson gson = new Gson();
String listString = gson.toJson(
items,
new TypeToken<ArrayList<Item>>() {}.getType());
try {
JSONArray jsonArray = new JSONArray(listString);
System.out.println(jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
midoalone
commented
Sep 30, 2017
I am using this and it actually works with me:
|
Hi:
I have checked this and it is not working when I was trying to set directly the dog object. Checking on Google I found that for directly access you must register the type adapter for the dog class directly like this:
Source:
https://gist.github.com/Retistic/9afece43e3d01f017f8b