姬長信(Redy)

如何在Android上的Retrofit中处理可能是ARRAY或…


我遇到的问题是我正在解析的API为大小为1的ARRAY返回一个OBJECT.

例如,有时API会响应:

{
    "monument": [
        {
            "key": 4152,
            "name": "MTS - Corporate Head Office",
            "categories": {},
            "address": {}
        },
        {
            "key": 4151,
            "name": "Canadian Transportation Agency",
            "categories": {},
            "address": {}
        },
        {
            "key": 4153,
            "name": "Bank of Montreal Building",
            "categories": {},
            "address": {}
        }
    ],
}

但是,如果纪念碑阵列只有1个项目,它就变成了一个OBJECT(注意缺少[]括号),如下所示:

{
    "monument": {
        "key": 4152,
        "name": "MTS - Corporate Head Office",
        "categories": {},
        "address": {}
    }
}

如果我像这样定义我的模型,只返回一个项目时会出错:

public class Locations {
    public List monument;
}

如果只返回一个项目,我会收到以下错误:

Expected BEGIN_OBJECT but was BEGIN_ARRAY ...

如果我像这样定义我的模型:

public class Locations {
    public Monument monument;
}

并且API返回ARRAY我得到了相反的错误

Expected BEGIN_ARRAY  but was BEGIN_OBJECT ...

我无法在模型中定义多个具有相同名称的项目.
我该如何处理这个案子?

注意:我无法对API进行更改.