-
-
Save Hazer/34055c6e404c07cf2d19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() { | |
@Override | |
public boolean shouldSkipField(FieldAttributes f) { | |
return f.getDeclaringClass().equals(RealmObject.class); | |
} | |
@Override | |
public boolean shouldSkipClass(Class<?> clazz) { | |
return false; | |
} | |
}) | |
.registerTypeAdapter(token, new TypeAdapter<RealmList<RealmInt>>() { | |
@Override | |
public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException { | |
// Ignore | |
} | |
@Override | |
public RealmList<RealmInt> read(JsonReader in) throws IOException { | |
RealmList<RealmInt> list = new RealmList<RealmInt>(); | |
in.beginArray(); | |
while (in.hasNext()) { | |
list.add(new RealmInt(in.nextInt())); | |
} | |
in.endArray(); | |
return list; | |
} | |
}) | |
.create(); | |
// Convert JSON to objects as normal | |
List<MainObject> objects = gson.fromJson(json, new TypeToken<List<MainObject>>(){}.getType()); | |
// Copy objects to Realm | |
realm.beginTransaction(); | |
realm.copyToRealm(objects); | |
realm.commitTransaction(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ "name" : "Foo", | |
"ints" : [1, 2, 3] | |
}, | |
{ "name" : "Bar", | |
"ints" : [] | |
} | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainObject extends RealmObject { | |
private String name; | |
private RealmList<RealmInt> ints; | |
// Getters and setters | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RealmInt extends RealmObject { | |
private int val; | |
public RealmInt() { | |
} | |
public RealmInt(int val) { | |
this.val = val; | |
} | |
// Getters and setters | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment