您好我是Retrofit库的新手,我在解析一些json时遇到了问题。我已经在Stackoverflow上看了一些其他的解决方案,但我的问题没有太多运气。我试图让一个简单的Web服务工作。任何建议将不胜感激..
Json文件
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
请求方法
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 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 $
我理解错误是说数据是一个对象,它应该从一个数组开始,但我不能解决它..谢谢
答案 0 :(得分:7)
您正在混合Employees
和employeesclass
个类。请尝试使用此代码:
public class Employees {
@SerializedName(value="employees")
public List<employeesclass> employees;
public void setEmployees(List<employeesclass> employees) {
this.employees = employees;
}
// employeesclass definition
}
然后相应地更改您的界面和requestEmployeeData
方法
public interface EmployeesAPI {
@GET("/get_names.json")
public void getEmployees(Callback<Employees> response);
}