改造预期BEGIN_OBJECT但BEGIN_ARRAY [英] Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY

查看:155
本文介绍了改造预期BEGIN_OBJECT但BEGIN_ARRAY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的JSON解析,我使用广场的改造图书馆,就遇到了这个问题。

I'm fairly new to JSON parsing , I'm using the Retrofit library of Square and ran into this problem.

我试图解析此JSON的回复:

I'm trying to parse this JSON reponse:

[
      {
        "id": 3,
        "username": "jezer",
        "regid": "oiqwueoiwqueoiwqueoiwq",
        "url": "http:\/\/192.168.63.175:3000\/users\/3.json"
      },
      {
        "id": 4,
        "username": "emulator",
        "regid": "qwoiuewqoiueoiwqueoq",
        "url": "http:\/\/192.168.63.175:3000\/users\/4.json"
      },
      {
        "id": 7,
        "username": "test",
        "regid": "ksadqowueqiaksj",
        "url": "http:\/\/192.168.63.175:3000\/users\/7.json"
      }
]

下面是我的模型:

public class Contacts {

    public List<User> contacts;

}

...

public class User {

    String username;
    String regid;

    @Override
    public String toString(){
        return(username);
    }  

}

我的接口:

public interface ContactsInterface {

    @GET("/users.json")
    void contacts(Callback<Contacts> cb);

}

我的成功方法:

my success method:

@Override
public void success(Contacts c, Response r) {
    List<String> names = new ArrayList<String>();
    for (int i = 0; i < c.contacts.size(); i++) {
        String name = c.contacts.get(i).toString();
        Log.d("Names", "" + name);
        names.add(name);
    }
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, names);
    mSentTo.setAdapter(spinnerAdapter);
}

当我用我的成功方法,它引发错误

When I use it on my success method it throws the error

预计BEGIN_OBJECT但BEGIN_ARRAY在1号线列2

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column2

什么是错在这里?

推荐答案

现在您解析响应,如果它是格式是这样的:

Right now you are parsing the response as if it was formatted like this:

{
  "contacts": [
    { .. }
  ]
}

这是你期待的物体,根,但真正的数据实际上是一个数组的异常告诉你这个研究。这意味着你需要改变的类型是一个数组。

The exception tells you this in that you are expecting an object at the root but the real data is actually an array. This means you need to change the type to be an array.

最简单的方法是只用一个列表作为直接型的回调:

The easiest way is to just use a list as the direct type in the callback:

@GET("/users.json")
void contacts(Callback<List<User>> cb);

这篇关于改造预期BEGIN_OBJECT但BEGIN_ARRAY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆