Reputation: 11
Retrofit JSON GET request is returning null for a nested field. How can I access the UserID field data ? What am i doing wrong ? I don't know how to parse json using retrofit. Am familiar with parsing simple json using Retrofit but am not familiar with parsing nested Json using Retrofit.
JSON Data:
{
"Status": "Success",
"ErrorMessage": null,
"ErrorKey": null,
"RedirectUrl": null,
"Data": {
"UserDetails": {
"UserID": "d7a6397c-fa33-4268-a64a-b99d0e78dfcf"
}
}
}
GetData Interface:
@GET("Account/LoginAPi")
Call<LoginResponse> getUser(@Query("UserName") String username,
@Query("Password") String password);
POJO:
public class LoginResponse {
@SerializedName("UserName")
String UserName;
@SerializedName("Password")
String Password;
@SerializedName("UserID")
String UserID;
@SerializedName("Status")
String Status;
public LoginResponse(String UserName, String Password, String UserID, String Status)
{
this.UserName = UserName;
this.Password = Password;
this.UserID = UserID;
this.Status = Status;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password){
this.Password = Password;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName){
this.UserName = UserName;
}
public String getUserID() {
return UserID;
}
public void setUserID(String UserID) {
this.UserID = UserID;
}
public String getStatus() {
return Status;
}
public void setStatus(String Status) {
this.Status = Status;
}
}
MainActivity:
GetData service = RetrofitClient.getRetrofitInstance().create(GetData.class);
Call<LoginResponse> call = service.getUser(username, password);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
pDialog.dismiss();
try {
String userid = response.body().getUserID();
toast(userid);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
}
});
Upvotes: 0
Views: 254
Reputation: 13947
Your login response class does not match the json that you gave, that's your problem.
I usually parse json files easily by using jsonschema2pojo website
Paste your json in there:
-------------- Data --------------------
public class Data {
@SerializedName("UserDetails")
public UserDetails userDetails;
}
-------------- LoginResponse ------------
package com.example;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("Status")
public String status;
@SerializedName("ErrorMessage")
public Object errorMessage;
@SerializedName("ErrorKey")
public Object errorKey;
@SerializedName("RedirectUrl")
public Object redirectUrl;
@SerializedName("Data")
public Data data;
}
-----------------------------------com.example.UserDetails.java-----------------------------------
package com.example;
import com.google.gson.annotations.SerializedName;
public class UserDetails {
@SerializedName("UserID")
public String userID;
}
Upvotes: 1