【问题标题】:expected begin array but was begin object预期开始数组,但开始对象
【发布时间】:2019-05-08 07:26:33
【问题描述】:

我是一个非常新的改造者。我想从服务器获取一些数据。但我无法做到这一点。请帮助我。当我调用 api 时,然后显示一个错误“预期的开始数组但是开始对象”。

 private void getCatagories(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Api.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
            .build();

    Api api = retrofit.create(Api.class);
    Call<List<Catagoty>> call = api.getCatagories();
    Log.e("this",Api.BASE_URL+"");
    call.enqueue(new Callback<List<Catagoty>>() {
        @Override
        public void onResponse(Call<List<Catagoty>> call, Response<List<Catagoty>> response) {
            List<Catagoty> catagotiesList = response.body();
            //Creating an String array for the ListView
            String[] heroes = new String[catagotiesList.size()];

            //looping through all the heroes and inserting the names inside the string array
            for (int i = 0; i < catagotiesList.size(); i++) {
                heroes[i] = catagotiesList.get(i).getSubCatagoryDescription();
            }


            //displaying the string array into listview
            listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, heroes));

        }

        @Override
        public void onFailure(Call<List<Catagoty>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}

【问题讨论】:

  • 可能收到的数据格式与您的预期不同。请在此处发布回复。
  • 你需要展示 Catagoty 类!
  • @SerializedName("Id") 私有整数 ID; @SerializedName("SubCatagoryDe​​scription") 私有字符串 SubCatagoryDe​​scription; public int getID() { 返回 ID; } 公共字符串 getSubCatagoryDe​​scription() { 返回子类别描述; } public Catagoty(int ID, String subCatagoryDe​​scription) { this.ID = ID;子类别描述 = 子类别描述; }
  • 这是我的分类类

标签: android


【解决方案1】:

正如您所期望的那样,当 GSON 进行转换时,它期望得到一个 JSON 类别的数组,因此它可以将其转换为类别列表。

您遇到的错误是由 JSON 响应的第一个字符引起的

JSON 响应应该如下所示。似乎 api 响应实际上是返回一个 Catagoty 对象而不是一个列表,或者它可能是一个顶级 JSON 对象,它包装了一个 Catagoty 对象数组

[
  {
		"Id": 1,
		"SubCatagoryDescription": "Description 1"
	},
	{
		"Id": 2,
		"SubCatagoryDescription": "Description 2"
	}
]

【讨论】:

  • 那么响应的正文是否以[ 开头?
  • 你能调试响应并查看错误的确切位置吗?
  • 另外,我刚刚发现这篇文章可能有用。 stackoverflow.com/questions/36656827/… OP 导入了错误的字符串类型(com.sun.org.apache.xpath.internal.operations.String 而不是 java.lang.String),这弄乱了 GSON 的反序列化。
  • 我知道这与您的错误消息并不完全相同,但这让我认为您的 Catagoty 课程可能存在问题。您可以发布整个课程,包括导入和整个 api JSON 响应吗?
猜你喜欢
  • 2021-05-03
  • 2020-11-20
  • 2018-07-20
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多