Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit throwing error Expected BEGIN_ARRAY but was BEGIN_OBJECT

Hi I am new to the Retrofit library, I am having problems parsing some json. I have looked at some other solutions on Stackoverflow but not having much luck with my problem. im trying to get a a simple webservice to work. any suggestions would be gratefully appreciated ..

Json file

{"employees":[
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}

Request method

public void requestEmployeeData(String uri){
        RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
        EmployeesAPI employeesAPI =adapter.create(EmployeesAPI.class);
        employeesAPI.getEmployees(new Callback<List<Employees.employeesclass>>() {
            @Override
            public void success(List<Employees.employeesclass> employees, Response response) {
                List<String> names = new ArrayList<String>();
                Log.v("nas", "The Employees Webservice Success" + response);
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                Log.v("nas", "The Employees Webservice Failed " + retrofitError);
            }
        });
    }

Employees.java

public class Employees {
// List<String> listOfStrings = new ArrayList<String>();
@SerializedName(value="employees")
public List<Employees> employees;

public void setEmployees(List<Employees> employees) {
    this.employees = employees;

}

public static class employeesclass {
    String firstName;
    String lastName;


    @Override
    public String toString() {
        return (firstName + " " + lastName);

    }
}

}

EmployeesAPI.java

public interface EmployeesAPI {
@GET("/get_names.json")
public void getEmployees(Callback<List<Employees.employeesclass>> response);
}

the error im getting is

The Employees Webservice Failed retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I understand the error is saying the data is an object and it should start with an array but I cant work it out.. Thanks

like image 559
n4zg Avatar asked Oct 08 '14 20:10

n4zg


1 Answers

You are mixing Employees and employeesclass classes. Try to use this instead:

public class Employees {

    @SerializedName(value="employees")
    public List<employeesclass> employees;

    public void setEmployees(List<employeesclass> employees) {
        this.employees = employees;

    }

    // employeesclass definition

}

Then change your interface and requestEmployeeData method accordingly

public interface EmployeesAPI {
    @GET("/get_names.json")
    public void getEmployees(Callback<Employees> response);
}
like image 152
Salem Avatar answered Oct 24 '22 03:10

Salem