简体   繁体   English

如何在 Android Studio 中使用 Retrofit 2 解析复杂的 JSON

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

I am trying to get the stopId from this API but I am having a hard time parsing it using retrofit 2 + gson.我正在尝试从此 API 获取 stopId,但我很难使用改造 2 + gson 解析它。 I've only got experience with less complicated JSON API's.我只有使用不太复杂的 JSON API 的经验。 Could anyone help me?有人可以帮助我吗?

{
    "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": [

            ]
        }]
    }
}

Create your models automatically with this tool.使用此工具自动创建模型。 Just paste an example json response.只需粘贴一个示例 json 响应。 http://pojo.sodhanalibrary.com http://pojo.sodhanalibrary.com

Remember to check and edit types of your variables, sometimes they can be null.请记住检查和编辑变量的类型,有时它们可​​能为空。 After that make your call as usual.之后,像往常一样拨打你的电话。

You have to create proper models hierarchy, for example:您必须创建适当的模型层次结构,例如:

BaseModel :基本模型

public class BaseModel {
    String direction;
    Timetable timetable;
}

Timetable :时间表

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

Route :路线:

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

StationInterval :车站间隔

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

Interval :间隔

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

And make retrofit call as usual:并像往常一样进行改造调用:

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

A simple and efficient way of generating POJO from JSON is http://www.jsonschema2pojo.org/ After you have included the models generated from the above link, you can continue reading this if you need some info setting up Retrofit 2.0.从 JSON 生成 POJO 的一种简单有效的方法是http://www.jsonschema2pojo.org/在您包含从上述链接生成的模型后,如果您需要一些设置 Retrofit 2.0 的信息,可以继续阅读本文。

Now, you would have to define a interface for the APIs现在,您必须为 API 定义一个接口

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

Then create a class to get the retrofit client然后创建一个类来获取改造客户端

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;
    }
}

Then when you need to call the API do this,然后当你需要调用 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