Emanuel Emanuel - 1 year ago 167
JSON Question

Using Retrofit and GreenDao with nested json objects

I want to combine Retrofit and GreenDao but I have a problem with nested Json-Objects. My nested fields remain empty.

This is the Json DataStructure

"id": 1,
"street": "Streetname",
"zipcode": 12345,
"city": "MyCity",
"phone_number": "+123456789",
"position": "12.0000, 9.0000",
"company": {
"title": "CompanyName",
"group": {
"title": "GroupName"

My DaoGenerator looks like this

Entity customItem = schema.addEntity("CustomItems");

Entity company = schema.addEntity("Company");

Entity group = schema.addEntity("Group");

Property companyPropId = customItem.addLongProperty("companyId").notNull().getProperty();
customItem.addToOne(company, companyPropId);

Property groupPropId = company.addLongProperty("groupId").notNull().getProperty();
company.addToOne(group, groupPropId);

My problem is that customItem.getCompany() returns null but the values "id" to "position" are fine. I'm not sure what the problem is as my CustomItem class contains the member

private Company company;

and the setter for the company and I can't see any typo.

public void setCompany(Company company) {
if (company == null) {
throw new DaoException("To-one property 'companyId' has not-null constraint; cannot set to-one to null");
synchronized (this) {
this.company = company;
companyId = company.getId();
company__resolvedKey = companyId;

Answer Source

I got it running but I had multiple problems.

1) When I wanted to persist the CustomItem, Company, and Group I had the problem that the getters getCompany() and getGroup() returned null because they don't return the member directly but fetch it from the DB. Therefore I added a getter to the generated CustomItem entity class that simply returns the company member. Now I was able to insert company to the db. The getter looks like this:

// KEEP METHODS - put your custom methods here
public Company getCompanyLocal() {
    return company;

The same works for Company and Group, too. But there was another issue...

2) The second problem was the entity 'Group' as 'group' is a reserved SQL keyword. I see one solution and a bad workaround to this problem:

  • The good one is to change you json data from 'group' to i.e. 'business_group' and according to that change your DAOs. Done.

  • The bad workaround if you are in the same situation like me where you can't change the json you could do the following. I don't persist the group at all but can access it via the company. It somehow appears there. Therefore I added a getter to my Company class like the getter of CustomItem above. It works but you should avoid this. As you can't query your DB for group or load group from db.

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