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

我正在尝试使用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

参考方案

这很可能是您的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来拦截原始响应以查看问题是否在那里。

Java Double与BigDecimal - java

我正在查看一些使用双精度变量来存储(360-359.9998779296875)结果为0.0001220703125的代码。 double变量将其存储为-1.220703125E-4。当我使用BigDecimal时,其存储为0.0001220703125。为什么将它双重存储为-1.220703125E-4? 参考方案 我不会在这里提及精度问题,而只会提及数字…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

Java-父类正在从子类中调用方法? - java

抱歉,我还是编码的新手,可能还没有掌握所有术语。希望您仍然能理解我的问题。我想得到的输出是:"Cost for Parent is: 77.77" "Cost for Child is: 33.33" 但是,我得到这个:"Cost for Parent is: 33.33" "Cost f…

Java Map,如何将UTF-8字符串正确放置到地图? - java

我有一个地图,LinkedHashMap更确切地说。我想在上面放一个字符串对象。然后,我读取此值以查看实际存储的内容。字符串本身具有非ASCII字符(西里尔文,韩文等)。将其放到地图上然后阅读后,这些字符将替换为??? s。一些代码:Map obj = new LinkedHashMap(); System.out.println("name: &…

HIbernate创建数据库表 - java

我正在学习JPA-Hibernate。我正在关注这个article在Dog.java中,它被称为@Table(name = "dog")。 在persistence.xml中,我有以下内容<property name="hibernate.hbm2ddl.auto" value="create"…