gjackal gjackal - 6 months ago 172
JSON Question

Android: Mapping JSON into RealmObject with nested JSON objects doesn't work

I have a

JSON
string that contains a nested json like

{
"name": "name",
...
...
"profile": {
"id": 987,
"first_name": "first name"
...
...
}
}


I'm trying to map this
JSON
into
Realm
by using the method
realm.createObjectFromJson(Class clazz, String string)
and the problem is that the nested JSON is not mapped, the resulting
RealmObject
instance that corresponds to the
"profile"
has
0
's and
null
's for all the fields. I used
realm.beginTransaction()
before the create operation, and
realm.commitTransaction()
after.

I'm using
'io.realm:realm-android:0.80.1'
for my Android project.

Can you please tell me what am I doing wrong?

Thanks.

EDIT
These are my model classes. Simple RealmObjects linked together

public class SomeClass extends RealmObject {
private String name;
private Profile profile;

public Profile getProfile() {
return profile;
}

public String getName() {
return name;
}

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

public class Profile extends RealmObject {
private String firstName;
private String lastName;
private String birthdate;
private boolean newsLetter;
private boolean push;
private int userId;
private Date lastUpdate;
private RealmList<RealmAddress> addresses;
private RealmList<RealmGender> genders;
}


the profile class contains only getters and setters, and it contains other Strings and ints, which I deleted for the sake of simplicity.

Answer

Your JSON names doesn't match your child object field names which is why you don't see any data. Your profile name matches the field in SomeClass, which means the object gets created (with default values), but as none of the fields match in Profile, none of them are set.

firstName != first_name
userId != id   

If you want to have separate names in your JSON and the Java models you should use something like GSON (http://realm.io/docs/java/#gson) as that is not yet supported by Realm directly.