android - 预期开始数组但开始对象

标签 android

我是一个非常新的改造者。我想从服务器获取一些数据。但我无法做到这一点。请帮助我。当我调用 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();
        }
    });
}

最佳答案

正如您期望的那样,当 GSON 进行转换时,它期望的是 Catagoty 的 JSON 数组,因此它可以将其转换为 Catagoty 的列表。

您遇到的错误是由 JSON 响应的第一个字符引起的,该字符以 { 开头表示一个对象,但您期望 [ 表示一个对象JSON数组

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

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

关于android - 预期开始数组但开始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56035595/

相关文章:

Android - 使用 ArrayAdapter 一次向 ListView 添加和显示项目

java - 将Java位图转换为字节数组

java - 尝试启动进程时不调用 ProcessBuilder

iphone - 如何使用 Titanium 为 Android 和 iPhone 使用相同的布局?

Android 聊天实现建议

android - Azure Cosmos DB - 错误请求 - http :400

android - 如何从 TextView 中的按钮使用标准状态列表

安卓: "Class loader may fail for processes that host multiple applications"

java - 获取Android java数字常量/错误代码的字符串表示

Android获取图库图片Uri路径