2014-10-08 199 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

相關問題