简体   繁体   中英

Deserializing a list of JSON objects having object's ID as an object name

So I have this interesting Json from the Nest API that I need to parse but am having difficulty. Obviously, I dont have control over the JSON.

{
    "uyuyuyuuyieiehuhuhuhenne": {
        "name": "Cabin",
        "country_code": "US",
        "postal_code": "94304",
        "time_zone": "America/Los_Angeles",
        "away": "home",
        "structure_id": "uyuyuyuuyieiehuhuhuhenne"
    },
    "ryryryyryryyryrryyryryyr": {
        "name": "Boulder Home",
        "country_code": "US",
        "postal_code": "80302",
        "time_zone": "America/Denver",
        "away": "away",
        "structure_id": "ryryryyryryyryrryyryryyr"
    }
}

The object names are the id's of the object. I have an object called structures that contains a List but Im getting nothing in the conversion of the structure.

Assuming you have a POJO like:

@Getter
public class Structure {
    private String name;
    private String country_code;
    private String postal_code;
    private String time_zone;
    private String away;
    private String structure_id;
}

you can deserialize this JSON to a Map by using Gson TypeToken like:

Type t = new TypeToken<Map<String, Structure>>() {}.getType();
Map<String, Structure> map = new Gson().fromJson(JSON, t);

In other words your JSON is a map of Structure s having each Structure 's structure_id as a key.

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