简体   繁体   English

使用gson解析嵌套的JSON

[英]Parse a nested JSON using gson

{
    "Response": {
        "MetaInfo": {
            "Timestamp": "2011-11-21T14:55:06.556Z"
        },
        "View": [
            {
                "_type": "SearchResultsViewType",
                "ViewId": 0,
                "Result": [
                    {
                        "Relevance": 0.56,
                        "MatchQuality": {
                            "Country": 1,
                            "State": 1,
                            "County": 1,
                            "City": 1,
                            "PostalCode": 1
                        },
                        "Location": {
                            "LocationType": "point",
                            "DisplayPosition": {
                                "Latitude": 50.1105,
                                "Longitude": 8.684
                            },
                            "MapView": {
                                "_type": "GeoBoundingBoxType",
                                "TopLeft": {
                                    "Latitude": 50.1194932,
                                    "Longitude": 8.6699768
                                },
                                "BottomRight": {
                                    "Latitude": 50.1015068,
                                    "Longitude": 8.6980232
                                }
                            },
                            "Address": {
                                "Country": "DEU",
                                "State": "Hessen",
                                "County": "Frankfurt am Main",
                                "City": "Frankfurt am Main",
                                "District": "Frankfurt am Main",
                                "PostalCode": "60311",
                                "AdditionalData": [
                                    {
                                        "value": "Germany",
                                        "key": "CountryName"
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        ]
    }
}

I am trying to retrieve the postal code from the above JSON. 我正在尝试从上面的JSON中检索邮政编码。 I am using gson to parse it. 我正在使用gson来解析它。 I am very new to JSON and from what i read from all the posts here(some very similar to this), I understood that the fields name should be as it is. 我是JSON的新手,也是我从这里的所有帖子中读到的(有些非常相似),我明白字段名称应该是这样的。 So I understand i have to make 4 classes viz Response, view, Result and Address. 所以我理解我必须制作4个类,即响应,视图,结果和地址。 I made them static nested classes, but I am only getting null value as output. 我使它们成为静态嵌套类,但我只获得null值作为输出。 In the next JSON, I have multiple addresses. 在下一个JSON中,我有多个地址。 But I am stuck on this single response. 但我坚持这个单一的回应。

For a short example, I try to retrieve Timestamp with this code, but it gives me a null value 举一个简短的例子,我尝试用这段代码检索Timestamp,但它给了我一个空值

public class ParseJSON {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("try.json"));

        Gson gson = new GsonBuilder().create();
        Pojo pojo = gson.fromJson(br,Pojo.class);
        System.out.println(Pojo.Response.MetaInfo.Timestamp);
        br.close();
    }
}

class Pojo {
    public Pojo() { }

    static class Response{
        static class MetaInfo {
            static public String Timestamp;

            public String getTimestamp() {
                    return Timestamp;
            }
        }
    }
}

If you only need the "PostalCode" , you could use JsonParser instead of having a bunch of classes: 如果你只需要"PostalCode" ,你可以使用JsonParser而不是一堆类:

JsonParser jsonParser = new JsonParser();
JsonObject address = jsonParser.parse(json)
    .getAsJsonObject().get("Response")
    .getAsJsonObject().getAsJsonArray("View").get(0)
    .getAsJsonObject().getAsJsonArray("Result").get(0)
    .getAsJsonObject().get("Location")
    .getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();

or for all results: 或者所有结果:

JsonArray results = jsonParser.parse(json)
        .getAsJsonObject().get("Response")
        .getAsJsonObject().getAsJsonArray("View").get(0)
        .getAsJsonObject().getAsJsonArray("Result");
for (JsonElement result : results) {
    JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
    String postalCode = address.get("PostalCode").getAsString();
    System.out.println(postalCode);
}

To make your Timestamp example work, try: 要使您的Timestamp示例有效,请尝试:

public class ParseJSON {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("try.json"));

        Gson gson = new GsonBuilder().create();
        Pojo pojo = gson.fromJson(br, Pojo.class);

        System.out.println(pojo.Response.MetaInfo.Timestamp);
        br.close();
    }
}

class Pojo {
    Response Response = new Response();
}

class Response {
    MetaInfo MetaInfo = new MetaInfo();
}

class MetaInfo {
    String Timestamp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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