Andrew Cooper
Andrew Cooper

Reputation: 747

Getting a java.lang.ClassCastException when using net.sf.json.JSONObject with Googles Geocoding

I'm using Google's Geocoding API to get a JSON string containing geocode location information. Here's the string I am getting back from Google.

{
  "status": "OK",
  "results": [ {
"types": [ "street_address" ],
"formatted_address": "550 Susong Dr, Morristown, TN 37814, USA",
"address_components": [ {
  "long_name": "550",
  "short_name": "550",
  "types": [ "street_number" ]
}, {
  "long_name": "Susong Dr",
  "short_name": "Susong Dr",
  "types": [ "route" ]
}, {
  "long_name": "Morristown",
  "short_name": "Morristown",
  "types": [ "locality", "political" ]
}, {
  "long_name": "Morristown",
  "short_name": "Morristown",
  "types": [ "administrative_area_level_3", "political" ]
}, {
  "long_name": "Hamblen",
  "short_name": "Hamblen",
  "types": [ "administrative_area_level_2", "political" ]
}, {
  "long_name": "Tennessee",
  "short_name": "TN",
  "types": [ "administrative_area_level_1", "political" ]
}, {
  "long_name": "United States",
  "short_name": "US",
  "types": [ "country", "political" ]
}, {
  "long_name": "37814",
  "short_name": "37814",
  "types": [ "postal_code" ]
} ],
"geometry": {
  "location": {
    "lat": 36.2422740,
    "lng": -83.3219410
  },
  "location_type": "ROOFTOP",
  "viewport": {
    "southwest": {
      "lat": 36.2391264,
      "lng": -83.3250886
    },
    "northeast": {
      "lat": 36.2454216,
      "lng": -83.3187934
    }
  }
}

} ] }

However, when I run the following code in Java I get a "java.lang.ClassCastException: java.lang.String incompatible with net.sf.json.JSONObject" error.

  URL url = new URL(URL + "&address=" + URLEncoder.encode(address, "UTF-8") + "&signature=" + key);
  URLConnection conn = url.openConnection();
  ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
  IOUtils.copy(conn.getInputStream(), output);
  output.close();

  GAddress gaddr = new GAddress();
  JSONObject json = JSONObject.fromObject(output.toString());
  JSONObject placemark = (JSONObject) query(json, "Placemark[0]");

I'm not sure why I'm getting the error. The Google response looks like a valid JSON string to me. Anyone else had problems with this? I'm open to using something besides the net.sf.json if it doesn't play nice with Google for some reason.

Thanks,

Andrew

Upvotes: 0

Views: 2252

Answers (1)

Zeki
Zeki

Reputation: 5277

It looks like you are getting a string back from your original function call. To be sure, you could add

System.out.println(query(json, "Placemark[0]").class);

right before the last line. This will give you the type of the object you are dealing with.

Upvotes: 1

Related Questions