简体   繁体   English

使用Gson解析JSonObject进行建模

[英]Using Gson to Parse JSonObject to Model

I have the following model: I am trying to parse the response from the server using GSon, with the following code: 我有以下模型:我正在尝试使用GSon从服务器解析以下代码:

   public class UserDetails
    {
      private final int ID;
      private final String user_email;

      public UserDetails(int ID, String user_email)
     {
        this.ID = ID;
        this.user_email = user_email;
    }

    public int getID()
    {
        return ID;
    }

    public String getUser_email()
    {
        return user_email;
    }

   }


   public void onResponse(Call call, Response response) throws IOException {
       String mMessage = response.body().string();
       if (response.isSuccessful()) {
         try {
            Gson gson = new Gson();

            UserDetails user_details = gson.fromJson(mMessage, UserDetails.class);
            Log.d("Success","The response from the server" + " " + user_details.getID() 
               + " " + user_details.getUser_email().toString());
            Log.d("Success", " "+mMessage);
         }
       }
   }

However, when i place a break point to obtain the user details the values are always displayed as null. 但是,当我放置一个断点以获取用户详细信息时,这些值始终显示为null。

You have a non default constructor, and you don't seem to have a no arguments (default) constructor, as per the docs : 根据docs ,您有一个非默认构造函数,并且似乎没有无参数(默认)构造函数:

Please add one to your pojo: 请在您的pojo中添加一个:

 public UserDetails()
 {

}

If you want to be sure your POJO is well structured use this site . 如果您想确保POJO的结构合理,请使用此站点 It will generate the pojos based on your json structure. 它将根据您的json结构生成pojos。

This is roughly how it should look like: 大致如下所示:

public class UserDetail {

@SerializedName("ID")
@Expose
private Integer iD;
@SerializedName("user_email")
@Expose
private String userEmail;

public Integer getID() {
return iD;
}

public void setID(Integer iD) {
this.iD = iD;
}

public String getUserEmail() {
return userEmail;
}

public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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