如何使用gson

时间:2015-06-11 18:53:39

标签: android gson android-volley

我需要一个对象列表,但我遇到了问题。我很新用这个有帮助我的人吗?

我正在使用volley来获取jsonObject然后我需要转换它(我看到最好的wa是用gson做的)。下面你可以看看我的json的例子。

{
network: {
    company: "JCDecaux",
    href: "/v2/networks/dublinbikes",
    id: "dublinbikes",
    location: {
        city: "Dublin",
        country: "IE",
        latitude: 53.3498053,
        longitude: -6.2603097
    },
    name: "dublinbikes",
    stations: [
        {
            empty_slots: 37,
            extra: {
                address: "Fitzwilliam Square East",
                bonus: false,
                connected: "1",
                last_update: "1434047944",
                open: true,
                slots: 40,
                ticket: true,
                uid: 89
            },
            free_bikes: 3,
            id: "153ff4dfb7bd8912ef91c10849129c2e",
            latitude: 53.335211,
            longitude: -6.2509,
            name: "Fitzwilliam Square East",
            timestamp: "2015-06-11T18:41:31.11Z"
        },
        {
            empty_slots: 0,
            extra: {
                address: "Portobello Harbour",
                bonus: false,
                connected: "1",
                last_update: "1434047764",
                open: true,
                slots: 30,
                ticket: false,
                uid: 34
            },
            free_bikes: 30,
            id: "3c0cfd547a142bb651280991a412bcbe",
            latitude: 53.330362,
            longitude: -6.265163,
            name: "Portobello Harbour",
            timestamp: "2015-06-11T18:41:31.15Z"
        },

... ect

站班级

public class Station {
    public Station(){}

    public String StationName;
    public String Distance;
    public String Slots;
    public String Bikes;
    public String LastUpdate;

    //Getters and Setters ...
}

下面你可以看到我到目前为止做了什么..

 //stations
 JSONObject jsonNetwork = new JSONObject(response.getString("network"));

   Type listType = new TypeToken<ArrayList<Station>>() {
                }.getType();
   List<Station> yourClassList = new Gson().fromJson(jsonNetwork, listType);

但我不知道如何解析所有这些并避免我不需要的数据以及函数Gson().fromJson需要和JsonArray以及我所拥有的是JsonObject

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

如果您要寻找的只是车站,那么我认为您应该执行以下操作:

//stations
    JSONObject jsonNetwork = new JSONObject(response.getString("network"));
    JSONArray stationsArray = jsonNetwork.getJSONArray("stations");

现在,您应该将此stationsArray变量传递给 fromJson 方法。此外,您的Station类的变量名应该等于您要从json中提取的键名。以下链接有一个很好的例子:

http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

答案 1 :(得分:0)

使用以下代码

Gson gson = new Gson();
YourClass obj = gson.fromJson(jsonObject.toString(), YourClass.class);