gjackal gjackal - 2 years ago 374
JSON Question

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

I have a

string that contains a nested json like

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

I'm trying to map this
by using the method
realm.createObjectFromJson(Class clazz, String string)
and the problem is that the nested JSON is not mapped, the resulting
instance that corresponds to the
's and
's for all the fields. I used
before the create operation, and

I'm using
for my Android project.

Can you please tell me what am I doing wrong?


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download