0
votes

Using the Retrofit library to consume a service, I've added the code for my interface, model and also how I use the interface.

I keep getting a GSON throwing “Expected BEGIN_OBJECT but was BEGIN_ARRAY”

Interface

@GET("api/RetrofitAndroidArrayResponse")
    Call<student> getStudentDetails();

Model public class student {

    //Variables that are in our json
    private int StudentId;
    private String StudentName;
    private int StudentMarks;

    //Getters and setters
    public int getStudentId() {
        return StudentId;
    }

    public void setStudentId(int bookId) {
        this.StudentId = StudentId;
    }

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String name) {
        this.StudentName = StudentName;
    }

    public int getStudentMarks() {
        return StudentMarks;
    }

    public void setStudentMarks(String price) {
        this.StudentMarks = StudentMarks;
    }

}

How I call the method

        void getRetrofitObject() {

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            object service = retrofit.create(object.class);



            Call<student> call = service.getStudentDetails();

            call.enqueue(new Callback<student>() {
                @Override
                public void onResponse(Response<student> response, Retrofit retrofit) {

                    try {

                        text_id_1.setText("StudentId  :  " + response.body().getStudentId());
                        text_name_1.setText("StudentName  :  " + response.body().getStudentName());
                        text_marks_1.setText("StudentMarks  : " + response.body().getStudentMarks());

                    } catch (Exception e) {
                        Log.d("onResponse", "There is an error");
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFailure(Throwable t) {
                    Log.d("onFailure", t.toString());
                }
            });
        }
    }
2

2 Answers

1
votes

The response which you are receiving is in the Array format but you have your model as a Student object. Please provide the JSON response you received. Use HttpLoggingInterceptor to log the response.

0
votes

Thank you for your help

It stupid error. The call expected an object and was pointing to url that returned a list of objects.

I just changed the url and it worked find

 @GET("api/RetrofitAndroidObjectResponse")
    Call<Student> getStudentDetails();