How to get whole JSON response from api using Retrofit and GSON in android

时间:2019-01-07 12:56:05

标签: android gson retrofit

I am new to android and using retrofit for making api call which returns a json like below,I have made an api call using retrofit but it gives me only parent json array.not the nested one.So can any one help me how to get whole json as a response?

   ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<ProductResponse> call = apiService.getProducts();
        call.enqueue(new Callback<ProductResponse>() {
            @Override
            public void onResponse(Call<ProductResponse> call, Response<ProductResponse> response) {
                List<Category> categories = response.body().getResults();
                Log.d("cat", "Number of categories received: " + categories.size());
            }

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


public interface ApiInterface {

    @GET("/json")
    Call<ProductResponse> getProducts();

}


public class ApiClient {
    public static final String BASE_URL = "https://stark-spire-93433.herokuapp.com/";
    private static Retrofit retrofit = null;


    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

My JSON:

{
  "categories": [
    {
      "id": 1,
      "name": " Casuals",
      "products": [
        {
          "id": 1,
          "name": "Nike Sneakers",
          "date_added": "2016-12-09T11:16:11.000Z",
          "variants": [
            {
              "id": 1,
              "color": "Blue",
              "size": 42,
              "price": 1000
            },
            {
              "id": 2,
              "color": "Red",
              "size": 42,
              "price": 1000
            },
            {
              "id": 3,
              "color": "Blue",
              "size": 44,
              "price": 1200
            },

The above code is what i have treid,So can any one please help me for getting the whole response not only the parent category.

1 个答案:

答案 0 :(得分:0)

我想您使所有模型类都正确。 然后 替换

@GET("/json")
Call<ProductResponse> getProducts();

使用

@GET("json")
Call<ProductResponse> getProducts();

如果它不起作用,请发表评论。 我还将提供模型类。