简体   繁体   中英

how to pass a object of json to model - retrofit2

My response of my server is like:

{
"succ":true,
"result":[..]
}

I just pass the content of my result to my model. I don't make a separate model for above response.

for example:

@FormUrlEncoded
@POST("/category")
Call<List<CategoryPeramoonModel>> Category(@Field("id") String Title);


    Call<List<CategoryPeramoonModel>> call = ((App)getApplication()).getApiService().Category("0");
    call.enqueue(new Callback<List<CategoryPeramoonModel>>() {

        @Override
        public void onResponse(Call<List<CategoryPeramoonModel>> call, Response<List<CategoryPeramoonModel>> response) {

            Log.e("size",""+response.body().size());
            adapter.addItems(response.body());

        }

        @Override
        public void onFailure(Call<List<CategoryPeramoonModel>> call, Throwable t) {
            Log.e("error sliders",t.getMessage());
        }
    });

CategoryPeramoonModel is a model of result's content. but I got an error message.

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

I think the problem here is you're expecting List<CategoryPeramoonModel> but your API actually returns an object. To fix this you need to create a model for the response, something like below.

class MyResponse(
   val succ: Boolean,
   val result: List<CategoryPeramoonModel>
)

and then your API interface should look like this

Call<MyResponse> Category(@Field("id") String Title);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM