因为此json对象使用int作为字段密钥,所以在反序列化时无法指定字段密钥名称。因此,我需要首先从集合中提取值集合:
JsonParser parser = new JsonParser();JsonObject obj = parser.parse(json).getAsJsonObject();Set<Entry<String,JsonElement>> set = obj.entrySet();
现在,“ set”包含一组,在我的情况下是<1,{id:1,value:something}>。
因为这里的键没有用,所以我只需要值集,所以我迭代该集以提取值集。
for (Entry<String,JsonElement> j : set) { JsonObject value = (JsonObject) j.getValue(); System.out.println(value.get("id")); System.out.println(value.get("value")); }如果您拥有更复杂的结构(例如嵌套的json对象),则可以执行以下操作:
for (Entry<String,JsonElement> j : locations) { JsonObject location = (JsonObject) j.getValue(); JsonObject coordinate = (JsonObject) location.get("coordinates"); JsonObject address = (JsonObject) location.get("address"); System.out.println(location.get("location_id")); System.out.println(location.get("store_name")); System.out.println(coordinate.get("latitude")); System.out.println(coordinate.get("longitude")); System.out.println(address.get("street_number")); System.out.println(address.get("street_name")); System.out.println(address.get("suburb")); }希望能帮助到你。



