改造正在返回一个空的响应主体

时间:2019-05-08 00:03:27

标签: java android retrofit2

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。

我确保URL正确并且我的POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。

这是我要解析的JSON

{
"?xml": {
    "@version": "1.0",
    "@encoding": "utf-8"
},
"root": {
    "@id": "1",
    "uri": {
        "#cdata-section": "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=ANTC&json=y"
    },
    "date": "05/07/2019",
    "time": "02:00:01 PM PDT",
    "station": [
        {
            "name": "Antioch",
            "abbr": "ANTC",
            "etd": [
                {
                    "destination": "SFO/Millbrae",
                    "abbreviation": "MLBR",
                    "limited": "0",
                    "estimate": [
                        {
                            "minutes": "10",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        },
                        {
                            "minutes": "25",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        },
                        {
                            "minutes": "40",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        }
                    ]
                }
            ]
        }
    ],
    "message": ""
}

}

这是我的改造客户端/设置

public class RetrofitClient {

private static Retrofit sRetrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (sRetrofit == null) {
        sRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return sRetrofit;
}

public interface ApiInterface {

    // public API key
    @GET("api/etd.aspx?cmd=etd&key=MW9S-E7SL-26DU-VV8V&orig=ANTC&json=y")
    Call<Root> getData();
}

public class ApiUtils {

    public static final String BASE_URL = "http://api.bart.gov/";

    public static ApiInterface getApiInterface() {
    return RetrofitClient.getClient(BASE_URL).create(ApiInterface.class);
}

最后,这是我的onCreateView中的代码

    mService = ApiUtils.getApiInterface();
    mService.getData().enqueue(new Callback<TrainArrival>() {
        @Override
        public void onResponse(Call<TrainArrival> call, Response<TrainArrival> response) {
            if (response.isSuccessful()) {
                trainData = response.body();
                Log.d("TAG", new GsonBuilder().setPrettyPrinting().create().toJson(response));
            } else {
                int statusCode = response.code();
                Log.d("TAG", Integer.toString(statusCode));
            }
        }

        @Override
        public void onFailure(Call<TrainArrival> call, Throwable t) {
            Log.d("TAG", t.getMessage());
        }
    });
    Log.d("TAG", trainData.getDate());

这是响应。正文标签为空。

{
  "body": {},
  "rawResponse": {
    "body": {
      "contentLength": 731,
      "contentType": {
        "charset": "utf-8",
        "mediaType": "application/json; charset\u003dutf-8",
        "subtype": "json",
        "type": "application"
      }
    },
    "code": 200,
    "headers": {
      "namesAndValues": [
        "Cache-Control",
        "no-cache",
        "Pragma",
        "no-cache",
        "Content-Type",
        "application/json; charset\u003dutf-8",
        "Expires",
        "-1",
        "Server",
        "Microsoft-IIS/8.5",
        "Access-Control-Allow-Origin",
        "*",
        "X-AspNet-Version",
        "4.0.30319",
        "X-Powered-By",
        "ASP.NET",
        "Date",
        "Wed, 08 May 2019 00:02:00 GMT",
        "Content-Length",
        "731"
      ]
    },
    "message": "OK",
    "networkResponse": {
      "code": 200,
      "headers": {
        "namesAndValues": [
          "Cache-Control",
          "no-cache",
          "Pragma",
          "no-cache",
          "Content-Type",
          "application/json; charset\u003dutf-8",
          "Expires",
          "-1",
          "Server",
          "Microsoft-IIS/8.5",
          "Access-Control-Allow-Origin",
          "*",
          "X-AspNet-Version",
          "4.0.30319",
          "X-Powered-By",
          "ASP.NET",
          "Date",
          "Wed, 08 May 2019 00:02:00 GMT",
          "Content-Length",
          "731"
        ]
      },
      "message": "OK",
      "protocol": "HTTP_1_1",
      "receivedResponseAtMillis": 1557273722035,
      "request": {
        "cacheControl": {
          "immutable": false,
          "isPrivate": false,
          "isPublic": false,
          "maxAgeSeconds": -1,
          "maxStaleSeconds": -1,
          "minFreshSeconds": -1,
          "mustRevalidate": false,
          "noCache": false,
          "noStore": false,
          "noTransform": false,
          "onlyIfCached": false,
          "sMaxAgeSeconds": -1
        },
        "headers": {
          "namesAndValues": [
            "Host",
            "api.bart.gov",
            "Connection",
            "Keep-Alive",
            "Accept-Encoding",
            "gzip",
            "User-Agent",
            "okhttp/3.12.0"
          ]
        },
        "method": "GET",
        "tags": {
          "class retrofit2.Invocation": {
            "arguments": [],
            "method": {
              "artMethod": 502253502104,
              "override": false
            }
          }
        },
        "url": {
          "host": "api.bart.gov",
          "password": "",
          "pathSegments": [
            "api",
            "etd.aspx"
          ],
          "port": 80,
          "queryNamesAndValues": [
            "cmd",
            "etd",
            "key",
            "MW9S-E7SL-26DU-VV8V",
            "orig",
            "ANTC",
            "json",
            "y"
          ],
          "scheme": "http",
          "url": "http://api.bart.gov/api/etd.aspx?cmd\u003detd\u0026key\u003dMW9S-E7SL-26DU-VV8V\u0026orig\u003dANTC\u0026json\u003dy",
          "username": ""
        }
      },
      "sentRequestAtMillis": 1557273721989
    },
    "protocol": "HTTP_1_1",
    "receivedResponseAtMillis": 1557273722035,
    "request": {
      "headers": {
        "namesAndValues": []
      },
      "method": "GET",
      "tags": {
        "class retrofit2.Invocation": {
          "arguments": [],
          "method": {
            "artMethod": 502253502104,
            "override": false
          }
        }
      },
      "url": {
        "host": "api.bart.gov",
        "password": "",
        "pathSegments": [
          "api",
          "etd.aspx"
        ],
        "port": 80,
        "queryNamesAndValues": [
          "cmd",
          "etd",
          "key",
          "MW9S-E7SL-26DU-VV8V",
          "orig",
          "ANTC",
          "json",
          "y"
        ],
        "scheme": "http",
        "url": "http://api.bart.gov/api/etd.aspx?cmd\u003detd\u0026key\u003dMW9S-E7SL-26DU-VV8V\u0026orig\u003dANTC\u0026js

1 个答案:

答案 0 :(得分:0)

最有可能是您的POJO课。我只是有这个问题。

尝试创建仅包含根及其ID的类。现在。

class TrainArrival {

    public TrainArrival() {
    }

    @SerializedName("root")
    Root root;

    class Root {
        @SerializedName("@id")
        public int id;
    }
}

我刚刚注意到,您的getData()返回值与您的response不匹配。我很惊讶它甚至被编译。

应该是

public interface ApiInterface {

    // public API key
    @GET("api/etd.aspx?cmd=etd&key=MW9S-E7SL-26DU-VV8V&orig=ANTC&json=y")
    Call<TrainArrival> getData();
}

如果这不起作用,那么您需要通过创建自己的OkHttpClient来拦截原始响应以查看问题是否在那里。