Gson 抛出 "BEGIN_OBJECT expected but BEGIN_ARRAY found" - 如何使用 TypeToken

Gson throws "BEGIN_OBJECT expected but BEGIN_ARRAY found" - how to use TypeToken

第一次尝试 Gson 而不是循环遍历 JSON 对象以提高速度。

这是我解析的输入数据集

{
  "data": [
    {
      "access_token": "XXXXX", 
      "category": "Community", 
      "name": "Startup notes by Vrashabh", 
      "id": "XXXXX", 
      "perms": [
        "ADMINISTER", 
        "EDIT_PROFILE", 
        "CREATE_CONTENT", 
        "MODERATE_CONTENT", 
        "CREATE_ADS", 
        "BASIC_ADMIN"
      ]
    }, 
    {
      "access_token": "XXXX", 
      "category": "Community", 
      "name": "Clean Bangalore", 
      "id": "XXXXX", 
      "perms": [
        "ADMINISTER", 
        "EDIT_PROFILE", 
        "CREATE_CONTENT", 
        "MODERATE_CONTENT", 
        "CREATE_ADS", 
        "BASIC_ADMIN"
      ]
    }, 
    {
      "access_token": "XXXXX", 
      "category": "Internet/software", 
      "name": "Getmeetin", 
      "id": "XXXXX", 
      "perms": [
        "ADMINISTER", 
        "EDIT_PROFILE", 
        "CREATE_CONTENT", 
        "MODERATE_CONTENT", 
        "CREATE_ADS", 
        "BASIC_ADMIN"
      ]
    }
  ], 
  "paging": {
    "cursors": {
      "before": "MTU3MzE3MTA0MjkyMjY4MQ==", 
      "after": "MjcyMTIwMzE2Mjk3NzI5"
    }
  }
}

这是我的 gson 映射 class

public class AccountsResponse {
    ArrayList<AcResponseData> data;
    ArrayList<PagingData> paging;

    public class AcResponseData {
        public String access_token;
        public String category;
        public String name;
        public String id;
        public String[] perms;
    }
    public class PagingData{
        public Cursors cursors;
    }
    public class Cursors{
        public String before;
        public String after;
    }
}

解析数据的代码

AccountsResponse responseAccounts = gsonResponse.fromJson(response.getRawResponse(), AccountsResponse.class);

我知道我不应该期待数据转换方面的魔法,我在 SO 上发现了 other 问题,要求我实现 TypeToken,但我无法让它在这种情况下工作。如何使用 TypeToken 将这些数据导入 ORM 如果需要从 ORM

中删除,我不介意实际上也不读取该分页数据

更新 如下更改了 ORM,但现在我得到

java.lang.WhosebugError

问题出在您的 AccountsResponse class 上。它应该是一个对象 PagingData 而不是 ArrayList,因为根据您问题中的 json 响应,"paging" 是一个 JSON 对象而不是 JSON 大批。因此,您应该将 paging 声明为 PagingData 对象而不是 PagingData 对象的 ArrayList。那应该可以解决它。

public class AccountsResponse {
    ArrayList<AcResponseData> data;
    PagingData paging;

    public class AcResponseData {
        public String access_token;
        public String category;
        public String name;
        public String id;
        public String[] perms;
    }
    public class PagingData{
        public Cursors cursors;
    }
    public class Cursors{
        public String before;
        public String after;
    }
}

如果有帮助请告诉我。