android - 从 Android 中的 JSON 响应访问嵌套对象

标签 android retrofit2

我正在学习改造。以下是我的 json 响应:

 {
  "battingStyle": "Right-hand bat",
  "born": "April 24, 1973, Bombay (now Mumbai), Maharashtra",
  "bowlingStyle": "Right-arm offbreak, Legbreak googly",
  "country": "India",
  "creditsLeft": 248,
  "currentAge": "44 years 186 days",
  "data": {
    "batting": {
      "tests": {
        "50": "68",
        "100": "51",
        "4s": "",
        "6s": "69",
        "Ave": "53.78",      
      }
    }
  },

  "playingRole": "Top-order batsman",

}

我正在尝试将“测试”部分的值分配给 Tests POJO类。 但是所有字段都被初始化为 null。我哪里出错了?

我的界面代码:

public interface ApiInterface {
    @GET("playerStats")
    Call<PlayerData> getPlayerData(@Query("apikey")String apikey, @Query("pid") String pid);

我的 MainActivity 中的代码

  ApiInterface apiInterface = r.create(ApiInterface.class);
  Call<ODIs>call=apiInterface.getODIStats("apikey","pid");
  call.enqueue(new Callback<MatchData>() {
        @Override
        public void onResponse(Call<PlayerData> call, Response<PlayerData> response) {
            try {
                  JSONObject jsonObject = new JSONObject(newGson().toJson(response.body()));

                s=jsonObject.toString();
                Tests tests = new Gson().fromJson(s, Tests.class);

            }
          catch (Exception e){}

在这里,rRetrofit实例。如果我的代码是多余的,我很抱歉。我刚开始学习。如果我必须提供更多详细信息,请告诉我。

最佳答案

您必须通过每个级别,在本例中,首先是 data 对象,然后是 batting 对象,最后是 tests 对象。

JSONObject jsonObject = new JSONObject(newGson().toJson(response.body()));
JSONObject testsObj = jsonObject.getJSONObject("data").getJSONObject("batting").getJSONObject("tests");

Tests tests = new Gson().fromJson(testsObj.toString(), Tests.class);

请注意,为了使其正常工作,您必须使用 SerializedName 注释来标记 JSON 中的每个字段的名称,因为变量名称不可能以数字开头:

import com.google.gson.annotations.SerializedName;

public class Tests{
    @SerializedName("50")
    private String fifteen;

    @SerializedName("100")
    private String hundred;

    @SerializedName("4s")
    private String fourS;

    @SerializedName("6s")
    private String sixS;

    private String Ave;
}

关于android - 从 Android 中的 JSON 响应访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567183/

相关文章:

android - 可以重获焦点的EditText

java - View 的 contentDescription 不能与 TextToSpeech 一起正常工作

android - 从服务器获取的数据在房间数据库中复制了多次

android - 为什么我的 ImageButton 样式没有应用到我的 ImageButton?

java - 矩形不更新也不显示颜色

android - 如何为不同状态设置图像按钮背景图像?

java - 改造2:添加RequestInterceptor

android - 如何去除 Dagger Hilt 依赖注入(inject)周期

android - 照片未出现在 RecyclerView 中

php - 当我使用 android Retrofit2 将 uuid 发布(发送)到服务器时,我得到了不同的数字