2014-10-08 91 views
7

嗨我是新的改造库,我有问题解析一些JSON。我已经看过Stackoverflow上的其他一些解决方案,但没有很好的解决我的问题。即时通讯试图让一个简单的web服务工作。任何建议,将感激理解..改装抛出错误预计BEGIN_ARRAY,但是BEGIN_OBJECT

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 $ 

我理解错误是说的数据是一个对象,它应该有一个数组开始,但我不能工作了..谢谢

回答

7

你混合Employeesemployeesclass类。尝试使用它代替:

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); 
} 
+0

还重命名'员工/ employeesclass'喜欢的东西'EmployeesWrapper/Employee'例如应该更容易理解。 – Salem 2014-10-08 21:04:23

+1

谢谢。那工作..网络服务成功:-) – n4zg 2014-10-08 21:12:39

+0

谢谢你为我工作 – souttab 2015-11-03 05:52:49

相关问题