如何使用retrofit2.0获取JSONArray数据?

时间:2016-10-26 18:26:43

标签: android pagination android-recyclerview retrofit2

我的界面如下所示:

public interface newArtsApi {

    @GET("art/get_all_arts?page=1")
    Call<List<ArtsPagination>> getMovies(@Query("index") int index);}

另一个ServiceGenerator类如下所示:

public class ServiceGenerator {

    public static <S> S createService(Class<S> serviceClass) {

        OkHttpClient httpClient=new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(String.class, new StringDesirializer());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://...../clients/....../api/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient).build();

        return retrofit.create(serviceClass);

    }
}

我想使用Retrofit 2.0,jsonarry_data

这类数据

JSONARRAY_DATA

但我在解析此类数据时遇到错误。

2 个答案:

答案 0 :(得分:0)

ApiInterface apiService =                 ApiClient.getClient()创建(ApiInterface.class);

    Call<MoviesResponse> call = apiService.getTopRatedMovies(API_KEY);
    call.enqueue(new Callback<MoviesResponse>() {
        @Override
        public void onResponse(Call<MoviesResponse> call, Response<MoviesResponse> response) {
            int statusCode = response.code();

            // Log.w("ResponseCode ",response.body().getResults()+"");
            List<Movie> movies = response.body().getResults();
            recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.list_item_movie, getApplicationContext()));
        }

        @Override
        public void onFailure(Call<MoviesResponse> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());
        }
    });

答案 1 :(得分:0)

如果您想收到ArtsPagination列表,您的代码就可以了,问题出在服务器端,因为它的响应不在列表中。如果您只想接收一个对象,则需要在界面上更改此对象:

Call<ArtsPagination> getMovies(@Query("index") int index);

更改此设置,您还需要更新onResponseonFailure方法,以便将响应作为单个对象进行处理。