Prasanna Aarthi
Prasanna Aarthi

Reputation: 3453

Android - Retrofit exception Expected BEGIN_OBJECT but was BEGIN_ARRAY

I am new to GSON and retrofit, Here is my output model (Just for reference structure),

    public class Result1
    {
        public int TotalCount { get; set; }
    }

    public class Result2
    {
        public int PostId { get; set; }
        public int PostTypeId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public bool IsFeatured { get; set; }
        public string Thumbnail { get; set; }
        public string CreatedDate { get; set; }
        public int CreatedBy { get; set; }
    }



public class RootObject
  {
     @Expose
        private List<com.example.got_sample.Result2> Result2 = new ArrayList<com.example.got_sample.Result2>();

    public List<com.example.got_sample.Result1> getResult1() {
        return Result1;
        }

        public void setResult1(List<com.example.got_sample.Result1> Result1) {
        this.Result1 = Result1;
        }

        public List<com.example.got_sample.Result2> getResult2() {
        return Result2;
        }
        public void setResult2(List<com.example.got_sample.Result2> Result2) {
        this.Result2 = Result2;
        }
    //Similar for result1
            }

Here is my output

    [{"Result1":

[{"TotalCount":5}]},

    {"Result2":

    [{"PostId":6,"PostTypeId":1,"Title":"","Description":"something"..},{"PostId":7,"PostTypeId":1,"Title":"","Description":"something"..}]
    }]

This is my retrofit code

 postmethod.sendpostrequest(object, new Callback<RootObject>() {
                      @Override
                      public void failure(RetrofitError retrofitError) {
                          System.out.println(retrofitError.getMessage());
                      }

                    @Override
                    public void success(RootObject arg0,
                            retrofit.client.Response arg1) {
                        // TODO Auto-generated method stub

                    }
                  });

    This is the exception I get"

Expected BEGIN_OBJECT but was BEGIN_ARRAY"

I have tried replacing RootObject With List < Result2 > since I am only interested in result 2.In that case I am getting the response as null.Please help.

Upvotes: 0

Views: 1262

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

The root of your JSON is an array of Result1 objects, but your Callback method is for a single RootObject.

Try modifying your JSON to start with "{" and end with "}", to make the root an object instead of an array.

Upvotes: 1

Related Questions