I don't get to parse too much JSON code with Java because the biggest JSON source I work with is Twitter, and I always use the Twitter4J project to interact with their web services. But a few days ago while working on an Android project, I just wanted to access their "Twitter Trends" REST service, and I used Java and the json.org Java library that comes with Android to parse the Twitter Trends JSON feed like this:
try { JSONArray wrapper = new JSONArray(response); JSONObject trendsObject = wrapper.getJSONObject(0); String asOf = trendsObject.getString("as_of"); JSONArray trendsArray = trendsObject.getJSONArray("trends"); StringBuilder sb = new StringBuilder(); for (int i=0; i<trendsArray.length(); i++) { JSONObject trend = trendsArray.getJSONObject(i); sb.append("name: " + trend.getString("name") + "\n"); } return sb.toString(); } catch (JSONException e) { // handle the error here ... }
This little bit of Java/JSON code let me parse the Twitter Trends feed, which is documented here. As you can see from that documentation, the JSON I parsed looked like this:
[ { "created_at": "2010-07-15T22:31:11Z", "trends": [ { "name": "Premios Juventud", "url": "http://search.twitter.com/search?q=Premios+Juventud", "query": "Premios+Juventud" }, { "name": "#agoodrelationship", "url": "http://search.twitter.com/search?q=%23agoodrelationship", "query": "%23agoodrelationship" }, (this goes on for a while ...) { "name": "DulceMariaLivePJ", "url": "http://search.twitter.com/search?q=DulceMariaLivePJ", "query": "DulceMariaLivePJ" } ], "as_of": "2010-07-15T22:40:45Z", "locations": [ { "name": "Worldwide", "woeid": 1 } ] } ]
There might be a better way to parse this JSON text, but in the short time I had to work on this project, I found it necessary to first treat the JSON as an array, then extract my object as the first element of that array, as shown in these first two lines:
JSONArray wrapper = new JSONArray(response); JSONObject trendsObject = wrapper.getJSONObject(0);
Again, I'm not a JSON parsing expert, but this approach worked, while attempting to treat the entire, initial feed as a JSONObject did not work. (I wish I knew more about JSON so I could explain that properly, but at this point I only know what worked and what didn't work.)