Question

I'm trying to geocode an address and get the lat/lng coordinates in java. I'm able to geocode the address and have it return in a json object, but I'm unable to figure out how to use json-simple to parse the json below to get the lat/lng. Any help is appreciated.

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Minneapolis",
               "short_name" : "Minneapolis",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Hennepin County",
               "short_name" : "Hennepin County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Minnesota",
               "short_name" : "MN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Minneapolis, MN, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 45.05125,
                  "lng" : -93.193794
               },
               "southwest" : {
                  "lat" : 44.890144,
                  "lng" : -93.32916299999999
               }
            },
            "location" : {
               "lat" : 44.983334,
               "lng" : -93.26666999999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 45.05125,
                  "lng" : -93.193794
               },
               "southwest" : {
                  "lat" : 44.890144,
                  "lng" : -93.32916299999999
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

I've tried many different things, but this is my latest failure:

JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONObject results = (JSONObject) json.get("results");    <-- LINE 186
JSONArray geometry = (JSONArray) results.get("geometry");

for(int i = 0; i < geometry.size(); i++) {
    JSONObject p = (JSONObject) geometry.get(i);
    System.out.println(p);
}

It produces this stacktrace:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
    at com.AddressGeocoder.geocode(AddressGeocoder.java:186)
    at com.AddressGeocoder.<init>(AddressGeocoder.java:48)
    at com.Geocoder.main(Geocoder.java:7)
Was it helpful?

Solution 3

So let me break it down for you so you can understand in JSON's {} denotes an object [] denotes an array. Simple? Yeah.

visual breakdown

results 
   index 0 ->
            addressed_components(array)-->
                                       long_name(single entity)
                                       short_name(single entity)
                                       types(array)

            formatted_address(single entity)
            geometry(huge ass object with nested objects)
            types(array)
  • Basically, in the code you have right now results 0 index would contain "address_components", "formatted_address", "geometry", "types". (NOTE THIS IS ALL ONE OBJECT)

  • "Address_components" is a array.

  • Which contain multiple "Address_components."

  • "Geometry" is just a very very large object in which has many different attributes.

  • Lastly types is an array.


psuedo code to retrieve items from arrays, yo!

LOOP THROUGH JSON ARRAY
     ASSIGN OBJECT VALUES // getting different objects that are indexed in the array.

(if you want to see code to see how all this is done let me know)

gl man.

OTHER TIPS

"results" is a JSONArray filled with (in this example just one) JSONObjects. These JSONObjects contain your expected JSONArray "geometry". Following is your code modified, so it loops through the results and printing the geometry data:

JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONArray results = (JSONArray) json.get("results");
for (int i = 0; i < results.size(); i++) {
    // obtaining the i-th result
    JSONObject result = (JSONObject) results.get(i);
    JSONObject geometry = (JSONObject) result.get("geometry");
    JSONObject location = (JSONObject) geometry.get("location");
    System.out.println(location.get("lat"));
    System.out.println(location.get("lng"));
}

That's because the "results" is a JSONArray. Try:

JSONArray results = (JSONArray ) json.getJSONArray("results");

I use net.sf.json library but you can use the logic

Here is the code :

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class Test {

    static String str = "{  \"results\" : [ {    \"address_components\" : [   {      \"long_name\" : \"Minneapolis\",      \"short_name\" : \"Minneapolis\",      \"types\" : [ \"locality\", \"political\" ]   },   {      \"long_name\" : \"Hennepin County\",      \"short_name\" : \"Hennepin County\",      \"types\" : [ \"administrative_area_level_2\", \"political\" ]   },   {      \"long_name\" : \"Minnesota\",      \"short_name\" : \"MN\",      \"types\" : [ \"administrative_area_level_1\", \"political\" ]   },   {      \"long_name\" : \"United States\",      \"short_name\" : \"US\",      \"types\" : [ \"country\", \"political\" ]   }    ],    \"formatted_address\" : \"Minneapolis, MN, USA\",    \"geometry\" : {   \"bounds\" : {      \"northeast\" : {     \"lat\" : 45.05125,     \"lng\" : -93.193794      },      \"southwest\" : {     \"lat\" : 44.890144,     \"lng\" : -93.32916299999999      }   },   \"location\" : {      \"lat\" : 44.983334,      \"lng\" : -93.26666999999999   },   \"location_type\" : \"APPROXIMATE\",   \"viewport\" : {      \"northeast\" : {     \"lat\" : 45.05125,     \"lng\" : -93.193794      },      \"southwest\" : {     \"lat\" : 44.890144,     \"lng\" : -93.32916299999999      }   }    },    \"types\" : [ \"locality\", \"political\" ] }  ],  \"status\" : \"OK\"}";

    public static void main(String[] args) {
        parseAndCheckJsonObj(str, "");
    }

    static void parseAndCheckJsonObj(Object str, Object key) {
        /*
         * Check whether str is Valid JSON
         *  String i.e. started by { [ or not
         */
        if (JSONUtils.mayBeJSON(str.toString())) {
            try {

                if (JSONUtils.isArray(str)) {
                    /*if block Check for str as a Json Array*/
                    JSONArray rootArr = JSONArray.fromObject(str);
                    for (int i = 0; i < rootArr.size(); i++) {
                        parseAndCheckJsonObj(rootArr.get(i), key);
                    }
                } else {
                    /*else block Check for str as a Json Object*/
                    JSONObject rootObj = JSONObject.fromObject(str);

                    Iterator keyIter = rootObj.keys();
                    while (keyIter.hasNext()) {
                        Object objKey = keyIter.next();
                        parseAndCheckJsonObj(rootObj.get(objKey), objKey);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            if (key.equals("lat"))
                System.out.println("Latitude is : " + str);
            else if (key.equals("lng"))
                System.out.println("Longitude is : " + str);
            else
                System.out.println(key + " : " + str);
        }
    }
}

My Output is :

long_name : Minneapolis
short_name : Minneapolis
types : locality
types : political
long_name : Hennepin County
short_name : Hennepin County
types : administrative_area_level_2
types : political
long_name : Minnesota
short_name : MN
types : administrative_area_level_1
types : political
long_name : United States
short_name : US
types : country
types : political
formatted_address : Minneapolis, MN, USA
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
Latitude is : 44.983334
Longitude is : -93.26666999999999
location_type : APPROXIMATE
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
types : locality
types : political
status : OK
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top