0
votes

How can i parse this using retrofit? i'm getting the error BEGIN_OBJECT but was BEGIN_ARRAY

Right now, i'm parsing it this way..

Below is the adapter class

 public static RetroInterface getCommonPathInterface() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("myurl")
                .build();
        records= restAdapter.create(RetroInterface.class);
        return records;
    }

Below is the interface, RetroInterface.class

 @GET("/mypath")
        void getValue(

                Callback<MyBean> callback    
        );

This is how i call it in the main activity

 getCommonPathInterface().getValue(new Callback<MyBean>() {
@Override
                    public void success(MyBean myBean, Response response) {
                       inti = 0;

                    }

                    @Override
                    public void failure(RetrofitError error) {
                        int i = 0;
                    }

                });

Below is the json response

 [
    {
    id: "111",
    name: "Val1"
    },
    {
    id: "222",
    name: "Val2"
    }
    ]
3
How do you parse it at the moment? - Egor
please share your current json parsing code block. otherwise nobody can help you. From error message, it is very clear it is expecting a JSON Object as the root object, but it is getting a JSON array as the root one. - Amit K. Saha
Take a look :). I've edited the code - Abhilash
What are you used for parsing the JSON. Retrofit uses Gson by default to convert HTTP bodies to and from JSON - Bhavdip Sagar
Yup, its the default retrofit GSON. As of now i ain't doing anything from my side. Have used around 9 service calls, all worked fine...except for this JSON response. - Abhilash

3 Answers

2
votes

Yippi ! Got it working. Very simple solution. A small change in my callback method.

Instead of Callback<MyBean> callback used Callback<MyBean[]> callback. Problem solved ! :)

1
votes

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

{
   "contacts":[
      {
         "id":"111",
         "name":"Val1"
      },
      {
         "id":"222",
         "name":"Val2"
      }
   ]
}

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 to JSON object.

Thank you.

0
votes

I'm new to retrofit, but I was having this issue when I was dealing with a multi-class POJO and using code designed for a single-class POJO. Let me know if that's the case. Also, please paste a bit of code! :)