简体   繁体   中英

Parse key-value pair type data structures using gson

I am trying to parse following response using gson library:

{
    "successful": true,
    "resultObject": {
        "areas": {
            "New york": [{
                "id": 1,
                "name": "Some area 1 in NY"
            }, {
                "id": 2,
                "name": "Some area 2 in NY"
            }, {
                "id": 3,
                "name": "Some area 3 in NY"
            }],
            "San Fransisco": [{
                "id": 1,
                "name": "Some area 1 in SF"
            }, {
                "id": 2,
                "name": "Some area 2 in SF"
            }, {
                "id": 3,
                "name": "Some area 3 in SF"
            }],
            "New Jersey": [{
                "id": 1,
                "name": "Some area 1 in NJ"
            }, {
                "id": 2,
                "name": "Some area 2 in NJ"
            }, {
                "id": 3,
                "name": "Some area 3 in NJ"
            }]
        }
    }
}

I was trying to use

Pair<String, City[]>[] cities;

to parse the areas key but it is coming as null every time. Java code for City class:

public class City {
        private String id;

        private String name;

        public String getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "ClassPojo [id = " + id + ", name = " + name + "]";
        }
    }

Any help is appreciated.

If the whole json needs to be parsed, I suggest you use a custom class, like this one:

public class GsonContainer{
    public boolean successful;

    public ResultObject resultObject;

    public static class ResultObject{
        public Map<String, List<City>> areas;
    }
}//end class

If it is only the json under areas, use a Map<String,List<City>> instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM