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

时间:2016-11-12 18:53:49

标签: java android json gson retrofit

我正在尝试从此API获取stopId,但我很难使用retrofit 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": [

            ]
        }]
    }
}

3 个答案:

答案 0 :(得分:2)

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

<强> BaseModel

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

<强> StationInterval

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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