【问题标题】:How to parse complex JSON with Retrofit 2 in Android Studio如何在 Android Studio 中使用 Retrofit 2 解析复杂的 JSON
【发布时间】:2016-11-12 18:53:49
【问题描述】:

我正在尝试从此 API 获取 stopId,但我很难使用改造 2 + gson 来解析它。我只有使用不太复杂的 JSON API 的经验。有人可以帮我吗?

{
    "direction": "inbound",
    "timetable": {
        "$type": "Tfl.Api.Presentation.Entities.Timetable, Tfl.Api.Presentation.Entities",
        "departureStopId": "940GZZCRECR",
        "routes": [{
            "$type": "Tfl.Api.Presentation.Entities.TimetableRoute, Tfl.Api.Presentation.Entities",
            "stationIntervals": [{
                "$type": "Tfl.Api.Presentation.Entities.StationInterval, Tfl.Api.Presentation.Entities",
                "id": "0",
                "intervals": [{
                    "$type": "Tfl.Api.Presentation.Entities.Interval, Tfl.Api.Presentation.Entities",
                    "stopId": "940GZZCRLEB",
                    "timeToArrival": 2
                }, {
                    "$type": "Tfl.Api.Presentation.Entities.Interval, Tfl.Api.Presentation.Entities",
                    "stopId": "940GZZCRSAN",
                    "timeToArrival": 3
                }]
            }, {

            }, {

            }],
            "schedules": [

            ]
        }]
    }
}

【问题讨论】:

    标签: java android json gson retrofit


    【解决方案1】:

    使用此工具自动创建模型。只需粘贴一个示例 json 响应。 http://pojo.sodhanalibrary.com

    请记住检查和编辑变量的类型,有时它们可​​能为空。然后像往常一样拨打电话。

    【讨论】:

      【解决方案2】:

      您必须创建适当的模型层次结构,例如:

      基础模型

      public class BaseModel {
          String direction;
          Timetable timetable;
      }
      

      时间表

      public class Timetable {
          String $type;
          String departureStopId;
          List<Route> routes;
      }
      

      路线

      public class Route {
          String $type;
          List<StationInterval> stationIntervals;
          List<Integer> schedules;
      }
      

      站间隔

      public class StationInterval {
          String $type;
          int id;
          List<Interval> intervals;
      }
      

      间隔

      public class Interval {
          String $type;
          String stopId;
          int timeToArrival;
      }
      

      并像往常一样拨打改造电话:

       @GET("some_url")
       Call<BaseModel> loadSomeData();
      

      【讨论】:

      • 我想过这个,但我认为可能有更好的方法来做到这一点。不过,这似乎不错!当我实现它并且它有效时,我会给你打勾。
      • 另外,您可以创建自定义TypeAdapter,并实现自己的json解析机制,但我不建议您这样做。
      • 我不断收到此错误Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2。然而,这是我正在使用的 API link
      • 显示您的改造请求?
      【解决方案3】:

      从 JSON 生成 POJO 的一种简单有效的方法是 http://www.jsonschema2pojo.org/ 包含从上述链接生成的模型后,如果您需要一些设置 Retrofit 2.0 的信息,可以继续阅读本文。

      现在,您必须为 API 定义一个接口

      public interface MyAPI {
          @GET("/url")
          Call<ResponseModel> getData();
      }
      

      然后创建一个类来获取改造客户端

      public class MyDataClient {
      
          public static final String BASE_URL = "";
          private static Retrofit retrofit = null;
      
      
          public static Retrofit getClient() {
              if (retrofit==null) {
                  HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
                  logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                  OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
                  httpClient.addInterceptor(logging);
      
                  retrofit = new Retrofit.Builder()
                          .baseUrl(BASE_URL)
                          .addConverterFactory(GsonConverterFactory.create())
                          .client(httpClient.build())
                          .build();
              }
              return retrofit;
          }
      }
      

      那么当你需要调用 API 的时候做这个,

           MyAPI apiService =MyDataClient.getClient().create(MyAPI.class);
           Call<ResponseModel> call = apiService.getData();
           call.enqueue(new Callback<ResponseModel>() {
                      @Override
                      public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
                      }
                      @Override
                     public void onFailure(Call<ResponseModel> call, Throwable t){
                      }
              });
      

      【讨论】:

        猜你喜欢
        • 2019-02-20
        • 1970-01-01
        • 2019-04-20
        • 2018-04-12
        • 2020-10-08
        • 2020-06-07
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多