Retrofit - 如何解析具有不同类型元素的数组?

Retrofit - How parse array with different types of elements?

我收到这个 JSON 字符串:

{
    "response": [
    346,
    {
        "id": 564,
        "from_id": -34454802,
        "to_id": -34454802,
        "date": 1337658196,
        "post_type": "post"
    },
    {
        "id": 2183,
        "from_id": -34454802,
        "to_id": -34454802,
        "date": 1423916628,
        "post_type": "post"
    },
    {
        "id": 2181,
        "from_id": -34454802,
        "to_id": -34454802,
        "date": 1423724270,
        "post_type": "post"
    }]
}

我创建以下 类:

public class Response {
    @SerializedName("response")
    ArrayList<Post> posts;
}

public class Post {
    int id;
    int from_id;
    int to_id;
    long date;
    String post_type;
}

当我尝试解析响应时,出现错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 19 path $.response[0]

这是因为数组的第一个元素是数字。需要哪个型号才能运行无误?

Retrofit 不能直接响应它使用 Converter by default GsonConverter 可用。这就是为什么需要自定义 Converter 实现的原因。

这 post using-gson-to-parse-array-with-multiple-types 应该有助于实施。

要设置转换器,只需使用:

RestAdapter getRestAdapter(...) {
    return new RestAdapter.Builder()
            ...
            .setConverter(converter)
            ...
            .build();
}

你的模型 class 应该是这样的,模型对象总是应该像字符串或 ArrayList 与 class 对象或字符串 Object.If 你提到 int ,你会得到 illegalState 异常。

public class Pojo
{
    private Response[] response;

    public Response[] getResponse ()
    {
        return response;
    }

    public void setResponse (Response[] response)
    {
        this.response = response;
    }
}


public class Response
{
    private String id;

    private String to_id;

    private String from_id;

    private String post_type;

    private String date;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getTo_id ()
    {
        return to_id;
    }

    public void setTo_id (String to_id)
    {
        this.to_id = to_id;
    }

    public String getFrom_id ()
    {
        return from_id;
    }

    public void setFrom_id (String from_id)
    {
        this.from_id = from_id;
    }

    public String getPost_type ()
    {
        return post_type;
    }

    public void setPost_type (String post_type)
    {
        this.post_type = post_type;
    }

    public String getDate ()
    {
        return date;
    }

    public void setDate (String date)
    {
        this.date = date;
    }
}