我正在使用 Retrofit API 进行通信。我希望将 JSON 对象直接存储在 Retrofit Result Bean 中。我尝试了以下过程,它产生了空值。但是在使用 postman 时,结果是正确的。
下面是API的输出
{
"status": 101,
"message": "Ok",
"type": 1,
"data": {
"value": "adakdj4lkj43"
}
}
上面的数据字段根据在一个案例中输入的值在另一个案例日期不断变化此数据取决于类型
下面是我的ResponseBean
public class ResponseBean {
private int status = 0;
private String message = "";
private int type = 0;
private JSONObject data = new JSONObject();
}
在执行改造调用时,我将此数据作为 {} 获取,这意味着没有数据。请帮我解决这个问题。提前致谢。
最佳答案
我正在使用改造版本 2。在你的gradle文件中添加如下依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
像这样创建一个接口(interface)
public interface Api {
@FormUrlEncoded
@POST("Login")
Call<ResponseBean> loginUser(@Field("uuid") String email, @Field("PASS") String password );
}
我使用 this 生成了模型
添加以下类
public class ResponseBean {
private int status;
private String message;
private int type;
private Data data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
和数据类
public class Data {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
现在在您的 Activity
ResponseBean responseBean;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://localhost:8080/API/")
.build();
Api api = retrofit.create(Api.class);
Call<ResponseBean> call = api.loginUser("your_user_id","your_password");
call.enqueue(new Callback<ResponseBean>() {
@Override
public void onResponse(Call<ResponseBean> call, Response<ResponseBean> response) {
responseBean = response.body();
}
@Override
public void onFailure(Call<ResponseBean> call, Throwable t) {
}
});
现在您将 jsonobject 直接存储在 responsebean 中。希望这有帮助
关于android - 在 Android 中以 Json 对象的形式获取 Retrofit 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38041617/