Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY java java

Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY


Right now you are parsing the response as if it was formatted like this:

{  "contacts": [    { .. }  ]}

The exception tells you this in that you are expecting an object at the root but the real data is actually an array. This means you need to change the type to be an array.

The easiest way is to just use a list as the direct type in the callback:

@GET("/users.json")void contacts(Callback<List<User>> cb);


dependencies used :

compile 'com.squareup.retrofit2:retrofit:2.3.0'compile 'com.squareup.retrofit2:converter-gson:2.3.0'

json responses can be an array response or an object response or even a combination of both. See the following three cases

Case 1 : Parsing a json array response (OP's case)

This case applies to those json responses which are of the form [{...} ,{...}]

E.g.

[  {    "id": 3,    "username": "jezer",    "regid": "oiqwueoiwqueoiwqueoiwq",    "url": "http:\/\/192.168.63.175:3000\/users\/3.json"  },  .  .]

First create a model class for this array or just goto jsonschema2pojo and auto generate one like below

Contacts.java

public class Contacts {@SerializedName("id")@Exposeprivate Integer id;@SerializedName("username")@Exposeprivate String username;@SerializedName("regid")@Exposeprivate String regid;@SerializedName("url")@Exposeprivate String url;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getRegid() {return regid;}public void setRegid(String regid) {this.regid = regid;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}}

ContactsInterface

In this case you should return a list of objects like the following

public interface ContactsInterface {@GET("/users.json")Call<List<Contacts>> getContacts();}

Then make the retrofit2 call like the following

Retrofit retrofit = new Retrofit.Builder()            .baseUrl("baseurl_here")            .addConverterFactory(GsonConverterFactory.create())            .build();    ContactsInterface request = retrofit.create(ContactsInterface.class);    Call<List<Contacts>> call = request.getContacts();    call.enqueue(new Callback<List<Contacts>>() {        @Override        public void onResponse(Call<List<Contacts>> call, Response<List<Contacts>> response) {            Toast.makeText(MainActivity.this,response.body().toString(),Toast.LENGTH_SHORT).show();        }        @Override        public void onFailure(Call<List<Contacts>> call, Throwable t) {            Log.e("Error",t.getMessage());        }    });

response.body() will give you the list of objects

YOU MAY ALSO CHECK THE FOLLOWING TWO CASES FOR REFERENCE

Case 2 : Parsing a json object response

This case applies to those json responses which are of the form {..}

E.g.

{"id": 3,"username": "jezer","regid": "oiqwueoiwqueoiwqueoiwq","url": "http:\/\/192.168.63.175:3000\/users\/3.json"}

Here, we have the same object as above example. So the model class will be the same, but like above example we dont have an array of these objects - just one single object and hence we dont need to parse it as a list.

So make the following changes for an object response

public interface ContactsInterface {    @GET("/users.json")    Call<Contacts> getContacts();    }

Then make the retrofit2 call like the following

Retrofit retrofit = new Retrofit.Builder()            .baseUrl("baseurl_here")            .addConverterFactory(GsonConverterFactory.create())            .build();    ContactsInterface request = retrofit.create(ContactsInterface.class);    Call<Contacts> call = request.getContacts();    call.enqueue(new Callback<Contacts>() {        @Override        public void onResponse(Call<Contacts> call, Response<Contacts> response) {            Toast.makeText(MainActivity.this,response.body().toString(),Toast.LENGTH_SHORT).show();        }        @Override        public void onFailure(Call<Contacts> call, Throwable t) {            Log.e("Error",t.getMessage());        }    });

response.body() will give you the object

You may also check a common error while parsing json object response :"expected begin_array but was begin_object"

Case 3 : Parsing a json array inside json object

This case applies to those json responses which are of the form {"array_name":[{...} ,{...}]}

E.g.

    {    "contacts":          [            {             "id": 3,             "username": "jezer",             "regid": "oiqwueoiwqueoiwqueoiwq",             "url": "http:\/\/192.168.63.175:3000\/users\/3.json"            }         ]    }

You will need two model classes here since we have two objects(one outside and one inside the array).Generate it like below

ContactWrapper

public class ContactWrapper {@SerializedName("contacts")@Exposeprivate List<Contacts> contacts = null;public List<Contacts> getContacts() {return contacts;}public void setContacts(List<Contacts> contacts) {this.contacts = contacts;}}

You can use Contacts.java generated above for the list objects(generated for case 1)

So make the following changes for an object response

public interface ContactsInterface {    @GET("/users.json")    Call<ContactWrapper> getContacts();    }

Then make the retrofit2 call like the following

Retrofit retrofit = new Retrofit.Builder()            .baseUrl("baseurl_here")            .addConverterFactory(GsonConverterFactory.create())            .build();    ContactsInterface request = retrofit.create(ContactsInterface.class);    Call<ContactWrapper> call = request.getContacts();    call.enqueue(new Callback<ContactWrapper>() {        @Override        public void onResponse(Call<ContactWrapper> call, Response<ContactWrapper> response) {            Toast.makeText(MainActivity.this,response.body().getContacts().toString(),Toast.LENGTH_SHORT).show();        }        @Override        public void onFailure(Call<ContactWrapper> call, Throwable t) {            Log.e("Error",t.getMessage());        }    });

Here, the difference from case 1 is that we should use response.body().getContacts() instead of response.body() to get the list of objects

Some references for above cases :

case 1 : Parsing a json array response,case 2 : Parsing a json object response,mixed : Parsing json array inside another json object


in your interfacereplace

@GET("/users.json")void contacts(Callback<Contacts> cb);

By this code

@GET("/users.json")void contacts(Callback<List<Contacts>> cb);