簡體   English   中英

如何在 Android Studio 中使用 Retrofit 2 解析復雜的 JSON

[英]How to parse complex JSON with Retrofit 2 in Android Studio

我正在嘗試從此 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": [

            ]
        }]
    }
}

使用此工具自動創建模型。 只需粘貼一個示例 json 響應。 http://pojo.sodhanalibrary.com

請記住檢查和編輯變量的類型,有時它們可​​能為空。 之后,像往常一樣撥打你的電話。

您必須創建適當的模型層次結構,例如:

基本模型

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();

從 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){
                }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM