我正在使用Retrofit,我想在Android中获得这种类型的对象。谁能解释一下我怎么才能拿到?我可以成功地获得一个简单的对象,但当它在一个对象中时,我得到的响应体为空。
这是JSON
{
"success": {
"token": "djhfeieryueyjsdheirydjalbbvcxgdgfhjdgs",
"name": "abc"
}
}
发布于 2020-07-12 17:40:03
这将取决于您从改进调用中选择的返回值。
例如,将该响应转换为POJO POJO将为
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
@SerializedName("success")
@Expose
private Success success;
public Success getSuccess() {
return success;
}
public void setSuccess(Success success) {
this.success = success;
}
}
-----------------------------------com.example.Success.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Success {
@SerializedName("token")
@Expose
private String token;
@SerializedName("name")
@Expose
private String name;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
所以你的网络调用应该是
`@POST("api") Call<Example> Login(@Body LoginRequest loginRequest);`
要访问它,它将看起来像(伪)
public static void login(String uname, String pword) {
Call<Example> getDataResponseSingle = retroInterface.Login(new LoginRequest(uname, pword));
getDataResponseSingle.enqueue()
new Call<Example>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Example dataResponse) {
dataResponse.getSuccess().getToken;
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
});
}
您还可以查看:http://www.jsonschema2pojo.org/来创建您自己的POJO
I您将直接返回一个JSON Object
,例如Call<JSONObject> getDataResponseSingle = retroInterface.Login(new LoginRequest(uname, pword));
在您看到成功响应的地方,您可以访问内部类(伪)
JSONObject main = response.body();
JSONObject success = main.getJSONObject("success");
https://stackoverflow.com/questions/62859344
复制相似问题