A couple of weeks ago I wrote an article and small demo of a REST web service call returning XML. It was my intention to do the same demo using JSON. However, I ran into a small sang; I couldn't get the Apex JSONObject to work. I worked on the code for most of the week before Christmas but couldn't beat it into submission. I may be a tad dense but I looked through the code, made a couple of changes but couldn't get the thing to work.

I was able to parse some simple JSON objects but complex objects did not want to cooperate. I received a couple of responses from Twitter and not many people have had much luck using the JSONObject with complex responses.

I started by downloading the JSONObject class from here and installed it into my Developer org. Then to use the Google Maps API Services I signed up for an API key and then took a look at their geocoding docs for JSON.

I started off by trying to parse the JSON response from their example URL. I executed the following code anonymously:

JSONObject jsonObject;
HttpRequest req = new HttpRequest();
Http http = new Http();

String url = 'http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=json&sensor=false&key=MY_API_KEY';

HTTPResponse resp = http.send(req);
JSONObject j = new JSONObject( resp.getBody() );

This produced the error:

System.TypeException: Invalid integer: -122.0843700
The JSON parser was supposed to return a string when it was not able to parse a value but it appeared to be choking on non-integers. I added the following to line 1374 before the value was returned:
new value( Integer.valueof(s) );
That at least seemed to fix the parsing problem, but now line 1335 was throwing a new error:
"Missing value"
I gave up hope using the Google Maps geocoding and thought I'd try a different approach. Yahoo! Web Services has really good JSON service so I thought I would try and use this JSON response. My code executed successfully and I didn't receive any errors parsing the JSON response. My only problem was that I couldn't really debug it much as I received the following message due to all of the parsing of the values:
*********** MAXIMUM DEBUG LOG SIZE REACHED ***********
So now I'm kind of stuck. Ron Hess offered to help out and take a look. I'm sure other people would like to use the JSONObject Apex class!