如何在Spring中使用Gson解析结果中的数据

时间:2015-08-21 12:17:48

标签: json spring gson

我正在尝试从服务器获取数据并将响应存储在

下面的结果中
ResponseEntity<String> result = restTemplate.exchange("https://jira.example.com/rest/api/id",  HttpMethod.GET, new HttpEntity<String>(createHeaders()), String.class);

    result = <200 OK,{
        "ipinfo": {
            "ip_address": "131.208.128.15",
            "ip_type": "Mapped",
            "Location": {
                "continent": "north america",
                "latitude": 30.1,
                "longitude": -81.714,
                "CountryData": {
                    "country": "united states",
                    "country_code": "us"
                },
                "region": "southeast",
                "StateData": {
                    "state": "florida",
                    "state_code": "fl"
                },
                "CityData": {
                    "city": "fleming island",
                    "postal_code": "32003",
                    "time_zone": -5
                }
            }
        }
    }>

我试过这个,但要求我将结果类型更改为字符串,但如果我更改我将在resttemplateexchange();

时收到错误
  JsonElement jelement = new JsonParser().parse(result);
        JsonObject  jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("ipinfo");

1 个答案:

答案 0 :(得分:1)

String json = result.getBody();   

JsonElement jelement = new JsonParser().parse(json);
JsonObject  jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("ipinfo");
[...]