Android json错误com.google.gson.JsonSyntaxException:java.lang.IllegalStateException

我在解析json数据时遇到此错误

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

我无法找到解决方案.我的json数据是:

{
  "user": [
    {
      "email": "wijden@jerseyrest.com",
      "firstName": "Wijden",
      "id": "1",
      "lastName": "User"
    }, {
      "email": "user@jerseyrest.com",
      "firstName": "Sample",
      "id": "2",
      "lastName": "User"
    }, {
      "email": "ingenieur@jerseyrest.com",
      "firstName": "Ingenieur",
      "id": "3",
      "lastName": "User"
    }
  ]
}

这就是我做到的方式:

Type type = new TypeToken<List<WorkItem>>() { }.getType();
List<WorkItem> workitems = (List<WorkItem>) new Gson().fromJson(resultat, type);

如果你能帮助我解决问题,我将不胜感激.提前致谢

最佳答案 为了解析你的JSON,我创建了包装响应的类,即:

public class Response {
  @SerializedName("user")
  private List<User> userList;
  //getters and setters
}

和,

public class User{
  @SerializedName("id")
  private int id;
  @SerializedName("email")
  private String email;
  @SerializedName("firstName")
  private String firstName;
  @SerializedName("lastName")
  private String lastName;
  //getters and setters
}

然后,为了解析您的JSON响应,您只需要:

Gson gson = new Gson();
Response data = gson.fromJson(yourJsonString, Response.class);

然后,您可以非常轻松地访问您的数据,例如:

User user = data.getUserList.get(i);

注意:使用注释@SerializedName对于分离JSON响应中和应用程序中的字段名称很有意义,以便遵循Java命名约定…

点赞