用gson反序列化内部类返回null

用gson反序列化内部类返回null

本文介绍了用gson反序列化内部类返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想用Gson将我的JSON反序列化为对象。
我定义了适当的类,其中一些类的对象包含在其他对象中。
当试图反序列化整个JSON时,我得到了空值,所以我开始将它分开。



我达到了所有低级别都支持它们的程度自我,但是当试图反序列化到一个持有该小对象的实例的对象时 - 每一件事都返回为null。



我的部分JSON:


$ b $

    类,它将包含类型为 UserProfile 的字段,名称为 user_profile : 

  public class UserProfileWrapper {
private UserProfile user_profile;
}

并解析这个 json 使用这个类的字符串:

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


This is my first time asking a question here, after 3 years of computer science, so bare with me.

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反序列化内部类返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:25