I need to get the lat and lng cords as separate string values. I decided to use GSON to help with this but am having issues getting the points. I'd prefer not to add any extra classes but it's not a deal breaker. I don't even care to use an easier solution without GSON if there is one.
Below is what I tried.
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"));
}
I can get the results string but not just the lat or lng. Plus it uses extra classes I was trying to avoid. Below is what the JSON returned from the URL looks like.
{
"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"
}
]
}
]
}
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");
Parse json String as Jsonobject
, and get value one by one. but I think the fastest way is creating a model to map the Json String Object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.