简体   繁体   中英

Deserializing inner class with gson returns null

I want to use Gson to Deserialize my JSON into objects. I've defined the appropriate classes, and some of those class' objects are included in other objects. When trying to deserialize the whole JSON, I got null values, so I started breaking it apart.

I reached the point where all lower classes stand by them selves, but when trying to deserialize into an object that holds an instance of that smaller object - every thing returns as null.

My partial JSON:

{
  "user_profile": {
    "pk": 1,
    "model": "vcb.userprofile",
    "fields": {
      "photo": "images/users/Screen_Shot_2013-03-18_at_5.24.13_PM.png",
      "facebook_url": "https://google.com/facebook",
      "site_name": "simple food",
      "user": {
        "pk": 1,
        "model": "auth.user",
        "fields": {
          "first_name": "blue",
          "last_name": "bla"
        }
      },
      "site_url": "https://google.com/"
    }
  }
}

UserProfile Class:

public class UserProfile {
    private int pk;
    private String model;
    private UPfields fields = new UPfields();//i tried with and without the "new"
}

UPfields Class:

public class UPfields {
    private String photo;
    private String facebook_url;
    private String site_name;
    private User user;
    private String site_url;
}

User Class:

public class User {
    private int pk;
    private String model;
    private Ufields fields;
}

Ufields Class:

public class Ufields {
    private String first_name;
    private String last_name;
}

In my main I call:

Gson gson = new Gson();
UserProfile temp = gson.fromJson(json, UserProfile.class);

So my temp object contain only null values. I've tried changing the classes to static, and it doesn't work. The UPfields object and all lower one work fine.

Any suggestions?

when I remove the

"{
  "user_profile":"

and it's closing bracket, the deserialize to a user_profile object works.

In order to parse this json example you have to create auxiliary class, which will contain field named user_profile of type UserProfile :

public class UserProfileWrapper {
    private UserProfile user_profile;
}

and parse this json string with this class:

UserProfileWrapper temp = gson.fromJson(json, UserProfileWrapper.class);

Gson starts by parsing the outermost object, which in your case has a single field, user_profile . Your UserProfile class doesn't have a user_profile field, so it can't deserialize it as an instance of that class. You should try to deserialize the value of the user_profile field instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM