如何获取RealmObject的JSONObject

时间:2017-11-22 04:17:48

标签: android json realm

我使用retrofit2来获取数据。并把它放入Realm。 但我不知道如何从jsonobject获取jsonobject并将其放入RealmObject。我应该在我的RealmObject模型中写什么?我是Realm DB的新手。 Thanx很多!

的JSONObject:

{
        "birth_date": "Fri, 12 Jul 1968 00:00:00 GMT",
        "gender": {
            "id": "male",
            "name": "Мужской"
        },
        "group": 1
    }

模型

public class PatientEntity extends RealmObject{

@SerializedName("gender") private RealmList<Gender> gender;

@SerializedName("birth_date")
String birth_date;

@SerializedName("group")
String group;

public String getBirth_date() {
    return birth_date;
}

public void setBirth_date(String birth_date) {
    this.birth_date = birth_date;
}

public RealmList<Gender> getGender() {
    return gender;
}

public void setGender(RealmList<Gender> gender) {
    this.gender = gender;
}

public String getGroup() {
    return group;
}

public void setGroup(String group) {
    this.group = group;
}}

性别模型类

public class Gender extends RealmObject{
@SerializedName("id")
String id;

@SerializedName("name")
String name;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

1 个答案:

答案 0 :(得分:0)

将构造函数添加到您的领域对象(PatientEntity.java),就像这样

public PatientEntity(){
}

public PatientEntity (String birth_date,String group){
this.birth_date=birth_date;
this.group=group;
}

将改进后的解析数据保存为字符串,假设birthgroup,将其传递给构造函数,如

PatientEntity patient=new PatientEntity (birth,group);

并将其添加到像这样的领域

realm.beginTransaction();
realm.copyToRealm(patient);
realm.commitTransaction();

注意:您需要在oncreate中初始化real以访问realm

***** **** EDIT

RequestInterface request = retrofit.create(RequestInterface.class);
    Call<PatientEntity> call1=request.getPOJO();
    call1.enqueue(new Callback<PatientEntity>() {
        @Override
        public void onResponse(Call<PatientEntity> call, Response<PatientEntity> response) {

            PatientEntity patient=response.body(); //get PatientEntity 
            Gender gender=response.body().getGender();  //get Gender

        }

        @Override
        public void onFailure(Call<PatientEntity > call, Throwable t) {                

    });