Retrofit JSON GET请求为嵌套字段返回null。如何访问UserID字段数据?我究竟做错了什么 ?我不知道如何使用改造来解析json。熟悉使用Retrofit解析简单的json,但不熟悉使用Retrofit解析嵌套的Json。
JSON数据:
{
"Status": "Success",
"ErrorMessage": null,
"ErrorKey": null,
"RedirectUrl": null,
"Data": {
"UserDetails": {
"UserID": "d7a6397c-fa33-4268-a64a-b99d0e78dfcf"
}
}
}
GetData接口:
@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) {
}
});
答案 0 :(得分:1)
您的登录响应类与您提供的json不匹配,这就是您的问题。
我通常通过使用jsonschema2pojo网站
轻松解析json文件在其中粘贴您的json:
-------------- 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;
}