Using Gson to Parse JSonObject to Model

时间:2018-04-18 18:15:32

标签: java android gson

I have the following model: I am trying to parse the response from the server using GSon, with the following code:

   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.

1 个答案:

答案 0 :(得分:0)

你有一个非默认的构造函数,根据docs,你似乎没有参数(默认)构造函数:

请在你的pojo中添加一个:

 public UserDetails()
 {

}

如果您想确保您的POJO结构合理,请使用此site。它会根据你的json结构生成pojos。

这大致应该是这样的:

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;
}

}