0

尝试在我的 android 应用程序中使用 gson 解析以下 json,但由于它的结构无法解决。

JSON

[
{
    "city": {
        "country": "Canada",
        "id": 1,
        "name": "Toronto",
        "province": "Ontario"
    }
},
{
    "city": {
        "country": "Canada",
        "id": 11,
        "name": "Ajax",
        "province": "Ontario"
    }
}
]

JAVA

public class LocationCityList {

    private List<LocationCityContainer> cities;


    public List<LocationCityContainer> getTrends() {
        return cities;
    }
    public void setTrends(List<LocationCityContainer> cities) {
        this.cities = cities;
    }

}

以下返回一个适当长度的数组,但之后我无法弄清楚如何自己获取城市对象。

Gson gson = new Gson();
Reader r = new InputStreamReader(getJSONData(url));       
LocationCityList[] objs = gson.fromJson(r, LocationCityList[].class);

非常感谢任何帮助。

4

2 回答 2

1

逗号太多。试试这个json(注意我在安大略之后删除了逗号):

[
{
    "city": {
        "country": "Canada",
        "id": 1,
        "name": "Toronto",
        "province": "Ontario"
    }
},
{
    "city": {
        "country": "Canada",
        "id": 11,
        "name": "Ajax",
        "province": "Ontario"
    }
}

]

我发现在遇到 json 问题时通过验证器运行我的 json 是有益的。http://jsonlint.com/是一个很好的资源。

于 2012-07-24T22:01:44.087 回答
0

好的,想通了。Java代码需要如下。

public class LocationCityList {

LocationCity city;

public LocationCity getLocationCity(){
    return city;
}   

}

public class LocationCity {
private String name;
private String id;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}

}

于 2012-07-25T12:42:51.613 回答