Skip to content

Instantly share code, notes, and snippets.

Created April 9, 2015 06:35
Show Gist options
  • Save cmelchior/1a97377df0c49cd4fca9 to your computer and use it in GitHub Desktop.
Save cmelchior/1a97377df0c49cd4fca9 to your computer and use it in GitHub Desktop.
Realm, GSON and primitive JSON arrays
// Make a custom Gson instance, with a custom TypeAdapter for each wrapper object.
// In this instance we only have RealmList<RealmInt> as a a wrapper for RealmList<Integer>
Type token = new TypeToken<RealmList<RealmInt>>(){}.getType();
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
public boolean shouldSkipClass(Class<?> clazz) {
return false;
.registerTypeAdapter(token, new TypeAdapter<RealmList<RealmInt>>() {
public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException {
// Ignore
public RealmList<RealmInt> read(JsonReader in) throws IOException {
RealmList<RealmInt> list = new RealmList<RealmInt>();
while (in.hasNext()) {
list.add(new RealmInt(in.nextInt()));
return list;
// Convert JSON to objects as normal
List<MainObject> objects = gson.fromJson(json, new TypeToken<List<MainObject>>(){}.getType());
// Copy objects to Realm
{ "name" : "Foo",
"ints" : [1, 2, 3]
{ "name" : "Bar",
"ints" : []
public class MainObject extends RealmObject {
private String name;
private RealmList<RealmInt> ints;
// Getters and setters
public class RealmInt extends RealmObject {
private int val;
public RealmInt() {
public RealmInt(int val) {
this.val = val;
// Getters and setters
Copy link

egpayawal commented Jul 9, 2018

I implemented your solution but its not working for me. Do you have an update code for parsing primitive array string or int?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment