如何获取 JSON 嵌套对象

How to get JSON nested object

我正在使用 Retrofit,我想在 Android 中获取这种类型的对象。任何人都可以解释我怎样才能得到?我可以成功获得一个简单的对象,但是当它在对象内部时,我得到的响应主体为空。

这是JSON

{
  "success": {
     "token": "djhfeieryueyjsdheirydjalbbvcxgdgfhjdgs",
     "name": "abc"         
  }
}

这取决于您从改造调用中选择的 return 值。

例如,将该响应转换为 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

我是 return 直接 JSON Object 例如 Call<JSONObject> getDataResponseSingle = retroInterface.Login(new LoginRequest(uname, pword));

在您看到成功响应的地方,您可以访问内部 class(伪)

JSONObject main = response.body();
JSONObject success = main.getJSONObject("success");