使用带有Java的GSON从HTTP请求获取JSON值

时间:2015-10-19 01:47:15

标签: java json http request gson

我需要将lat和lng线作为单独的字符串值。我决定使用GSON来帮助解决这个问题,但是在获得积分方面遇到了问题。我不想添加任何额外的课程,但它不是一个交易破坏者。如果没有GSON,我甚至不在乎使用更简单的解决方案。

以下是我的尝试。

private static String readAll(Reader rd) throws IOException {
                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1) {
                  sb.append((char) cp);
                }
                return sb.toString();
              }

              public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
                InputStream is = new URL(url).openStream();
                try {
                  BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                  String jsonText = readAll(rd);
                  JSONObject json = new JSONObject(jsonText);
                  return json;
                } finally {
                  is.close();
                }
              }
public static void main(String[] args) throws InterruptedException, IOException, JSONException {

    JSONObject json = readJsonFromUrl("http://open.mapquestapi.com/geocoding/v1/address?key=Fmjtd|luu821ual9,8w=o5-94aaqy&location=1448south4thstreetlouisvilleky");
    System.out.println(json.toString());
    System.out.println(json.get("results"));
}

我可以获得结果字符串,但不仅仅是lat或lng。此外,它还使用了我试图避免的额外课程。以下是从URL返回的JSON的内容。

{
    "info": {},
    "options": {},
    "results": [
    {
    "providedLocation": {
    "location": "address here"
    },
    "locations": [
    {
    "street": "address here",
    "adminArea6": "",
    "adminArea6Type": "Neighborhood",
    "adminArea5": "city name",
    "adminArea5Type": "City",
    "adminArea4": "County name",
    "adminArea4Type": "County",
    "adminArea3": "State name",
    "adminArea3Type": "State",
    "adminArea1": "US",
    "adminArea1Type": "Country",
    "postalCode": "zip here",
    "geocodeQualityCode": "P1AAX",
    "geocodeQuality": "POINT",
    "dragPoint": false,
    "sideOfStreet": "N",
    "linkId": "0",
    "unknownInput": "",
    "type": "s",
    "latLng": {
    "lat": 90.227222,
    "lng": -90.762007
    },
    "displayLatLng": {
    "lat": 90.227222,
    "lng": -90.762007
    },
    "mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=111111111,160&pois=purple4"
    }
    ]
    }
    ]
    }

1 个答案:

答案 0 :(得分:0)

    JsonParser parser = new JsonParser();
    JsonObject o = parser.parse(jsonStr).getAsJsonObject();
    JsonElement latLng = o.get("results")
            .getAsJsonArray().get(0)
            .getAsJsonObject().get("locations")
            .getAsJsonArray().get(0)
            .getAsJsonObject().get("latLng");

将json String解析为Jsonobject,并逐个获取值。但我认为最快的方法是创建一个模型来映射Json String Object。