有没有一种方法,realm createOrUpdateAllFromJson()可以读取嵌套的JSONArrays并创建内部的RealmObjects?

时间:2017-04-07 00:53:15

标签: java android realm

我与学生有以下JSON建模组:

"groups":[{
    "id": "1",
    "grade":"second",
    "group": "A",
    "students":[{
      "id": "1",
      "address": "rhonda@pugh.no",
      "name": "Geoffrey Guthrie",
      "phone": "475690",
      "parent": "Ronald Zhang",
      "diagnosis": "Whitehead",
    },        
    ...}],
...}]

以及它们各自的类如下(不包括setter和getter):

public class Student extends RealmObject {
   private String id;
   private String name;
   private String address;
   private String phone;
   private String parent;
   private String diagnosis;
}

public class Group extends RealmObject{
    private String id;   
    private String grade;    
    private String group;
    private RealmList<Student> students;
}

我的问题是如果方法 createOrUpdateAllFromJson ,如上所述,支持那些嵌套数组,或者我应该手动获取内部数组,然后调用相同的函数来创建学生列表每个小组?

1 个答案:

答案 0 :(得分:0)

不,您不需要手动获取内部数组,然后调用相同的函数来创建每个组的学生列表。但你将无法使用

  

JOSNArray的createOrUpdateAllFromJson()

  

用于JSONObject的createOrUpdateObjectFromJson()

因为createOrUpdate需要主键。但根据您的Json结构,根对象没有主键。我的代码块将描述该场景。

你的Json结构 -

{
"groups":[{
"id": "1",
"grade":"second",
"group": "A",
"students":[{
  "id": "1",
  "address": "rhonda@pugh.no",
  "name": "Geoffrey Guthrie",
  "phone": "475690",
  "parent": "Ronald Zhang",
  "diagnosis": "Whitehead"
  }]
 }]
}

据此,您的模型应如下 -

public class Students extends RealmObject {
    private String id;
    private String name;
    private String address;
    private String phone;
    private String parent;
    private String diagnosis;
}

public class Groups extends RealmObject {
    private String id;
    private String grade;
    private String group;
    private RealmList<Students> students;
}

public class BaseObject extends RealmObject {
    private RealmList<Groups> groups;
}

然后你的交易将是这样的 -

realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.createObjectFromJson(BaseObject.class, json);
        }
    });

您可以为群组和学生 ID 添加 @PrimaryKey 注释,以避免在必要时重复输入。希望这种结构能减少你的麻烦。