Guest User

Untitled

a guest
Jul 25th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // Make a custom Gson instance, with a custom TypeAdapter for each wrapper object.
  2. // In this instance we only have RealmList<RealmInt> as a a wrapper for RealmList<Integer>
  3. Type token = new TypeToken<RealmList<RealmInt>>(){}.getType();
  4. Gson gson = new GsonBuilder()
  5. .setExclusionStrategies(new ExclusionStrategy() {
  6. @Override
  7. public boolean shouldSkipField(FieldAttributes f) {
  8. return f.getDeclaringClass().equals(RealmObject.class);
  9. }
  10.  
  11. @Override
  12. public boolean shouldSkipClass(Class<?> clazz) {
  13. return false;
  14. }
  15. })
  16. .registerTypeAdapter(token, new TypeAdapter<RealmList<RealmInt>>() {
  17.  
  18. @Override
  19. public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException {
  20. // Ignore
  21. }
  22.  
  23. @Override
  24. public RealmList<RealmInt> read(JsonReader in) throws IOException {
  25. RealmList<RealmInt> list = new RealmList<RealmInt>();
  26. in.beginArray();
  27. while (in.hasNext()) {
  28. list.add(new RealmInt(in.nextInt()));
  29. }
  30. in.endArray();
  31. return list;
  32. }
  33. })
  34. .create();
  35.  
  36. // Convert JSON to objects as normal
  37. List<MainObject> objects = gson.fromJson(json, new TypeToken<List<MainObject>>(){}.getType());
  38.  
  39. // Copy objects to Realm
  40. realm.beginTransaction();
  41. realm.copyToRealm(objects);
  42. realm.commitTransaction();
Add Comment
Please, Sign In to add comment