【问题标题】:RETROFIT 2 Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2RETROFIT 2 预期为 BEGIN_ARRAY,但在第 1 行第 2 列为 BEGIN_OBJECT
【发布时间】:2017-10-12 00:12:10
【问题描述】:

我是改装新手,在简单的 HTTP 获取请求中遇到此错误(预期为 BEGIN_ARRAY,但在第 1 行第 2 列是 BEGIN_OBJECT)。这是代码。帮帮我..`

主要活动

private ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.pagination_list);


    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("https://www.googleapis.com/books/v1/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

    String apiKey = getResources().getString(R.string.API_KEY);

    GitHubClient client = retrofit.create(GitHubClient.class);
    Call<List<Volumes>> call = client.reposForUser(apiKey);

    call.enqueue(new Callback<List<Volumes>>() {
        @Override
        public void onResponse(Call<List<Volumes>> call, Response<List<Volumes>> response) {
            List<Volumes> repos = response.body();
            int responseCode = response.code();
            Log.v("Volumeinfo", "onResponse: "+ responseCode);

            listView.setAdapter(new GitHubRepoAdapter(MainActivity.this, repos));
        }

        @Override
        public void onFailure(Call<List<Volumes>> call, Throwable t) {

            Log.v("Volumeinfo", "onResponse: "+ t.getMessage());
            Toast.makeText(MainActivity.this, t.getMessage()+"error :(", Toast.LENGTH_LONG).show();
        }
    });
}

界面

{

@GET("volumes?q=Android+intitle")
Call<List<Volumes>> reposForUser(@Query("key")String ApiKey );
}




 public class Volumes {




 @SerializedName("title")
 @Expose
 private String title;


public String getTitle() {
    return title;
}

}

适配器

private Context context;
private List<Volumes> values;

public GitHubRepoAdapter(Context context, List<Volumes> values) {
    super(context, R.layout.list_item_pagination, values);

    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    if (row == null) {
        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.list_item_pagination, parent, false);
    }

    TextView textView = (TextView) row.findViewById(R.id.list_item_pagination_text);

    Volumes item = values.get(position);
    String message = item.getTitle();
    textView.setText(message);

    return row;
}
}

Json

   {
  "kind": "books#volumes",
  "totalItems": 3395,
  "items": [
   {
  "kind": "books#volume",
   "id": "1igDDgAAQBAJ",
   "etag": "oS4LeBsRcfg",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/1igDDgAAQBAJ",
    "volumeInfo": {
"title": "Android Programming",
"subtitle": "The Big Nerd Ranch Guide",
"authors": [
 "Bill Phillips",
 "Chris Stewart",
 "Kristin Marsicano"
],
"publisher": "Pearson Technology Group",
"publishedDate": "2017-01-30",
"description": "This is the eBook of the printed book and may not include 
",
"industryIdentifiers": [
 {
  "type": "ISBN_13",
  "identifier": "9780134706078"
 },
 {
  "type": "ISBN_10",
  "identifier": "0134706072"
 }
],
"readingModes": {
 "text": true,
 "image": true
},
"pageCount": 624,
"printType": "BOOK",
"categories": [
 "Computers"
 ],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.1.1.0.preview.3",
"panelizationSummary": {
 "containsEpubBubbles": false,
 "containsImageBubbles": false
    },
   "imageLinks": {
    "smallThumbnail": "http://books.google.com/books/content?  
 id=1igDDgAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
 "thumbnail": "http://books.google.com/books/content?
 id=1igDDgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
  },
        "language": "en",
        "previewLink": "http://books.google.com/books?

完整的Json https://www.googleapis.com/books/v1/volumes?q=Android+intitle

几乎到处搜索..帮助将不胜感激

【问题讨论】:

    标签: java android-studio networking httprequest retrofit2


    【解决方案1】:

    您的设置似乎已经设置改造来解析 json,所以这个答案也假设了。

    您收到的错误来自Gson,如果您查看它 - Expected BEGIN_ARRAY but was BEGIN_OBJECT - 它告诉您,在解析 json 时它期待一个数组,但得到了一个对象。

    错误的第二部分很容易理解。如果您查看您的 json,它以 { 开头,这是一个对象而不是数组(以 [ 开头)。那么为什么它需要一个数组呢?

    为此,您必须求助于您的改造接口声明。你说你的调用会返回一个List&lt;Volumes&gt;(Gson可以在json数组和java列表之间转换)。问题是返回的 json 是(如前所述)对象而不是列表,因此 gson 无法将其转换为列表。

    进一步查看您的模型,将其更改为仅返回 Volumes 是不够的,并且会导致更多错误。您基本上必须将您的 json 直接映射到 java 对象(除非您想使用非常不必要的自定义反序列化器)。

    通过直接映射到 java 我的意思是你必须想出一个代表根 json 元素的对象,然后是一个代表项目的对象(可以只是一个对象列表)等等。

    这是一个很棒的website,它不仅可以帮助您理解我的意思,还可以根据您的 json 为您生成模型。您将 json 粘贴到字段中,确保选择了正确的选项 - 源类型 json、注释样式 gson 等。甚至还有适用于 android studio 的插件。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      相关资源
      最近更新 更多