0
我需要将纬度线和lng线作为单独的字符串值。我决定使用GSON来帮助解决这个问题,但是我有点问题。我不想添加任何额外的类,但它不是一个交易断路器。如果没有GSON,我甚至不关心使用更简单的解决方案。从使用GSON和Java的HTTP请求获取JSON值
下面是我试过的。
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"
}
]
}
]
}
啊伟大的工作。但是,我怎样才能获得一个字符串变量中的lat和另一个字符串变量中的lng。我尝试了几件事,但没有运气。 –
'o.get( “结果”) .getAsJsonArray()得到(0) .getAsJsonObject()。获得( “位置”) .getAsJsonArray()得到(0) .getAsJsonObject()得到( “latLng”)。getAsJsonObject.get(“lat”)' – chengpohi
'o.get(“results”).getAsJsonArray()。get(0).getAsJsonObject()。get(“locations”).getAsJsonArray()。get (0).getAsJsonObject()。get(“latLng”)。getAsJsonObject.get(“lng”)' – chengpohi