Question

Having received the following response from Foursquare, when I try to parse it, I get the error below:

Response:

{"meta":{"code":200},"response":{"venues":[{"id":"4b1c3ce9f964a520d60424e3","name":"Folsom Lake Bowl","contact":{},"location":{"address":"511 East Bidwell","lat":38.67291745,"lng":-121.165447,"distance":39,"postalCode":"95630","city":"Folsom","state":"CA"},"categories":[{"id":"4bf58dd8d48988d1e4931735","name":"Bowling Alley","pluralName":"Bowling Alleys","shortName":"Bowling Alley","icon":{"prefix":"https://foursquare.com/img/categories/arts_entertainment/bowling_","sizes":[32,44,64,88,256],"name":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":592,"usersCount":284,"tipCount":2},"hereNow":{"count":0}}]}}

Error:

Exception in thread "main" org.codehaus.jettison.json.JSONException: JSONObject["groups"] not found.
at org.codehaus.jettison.json.JSONObject.get(JSONObject.java:360)
at org.codehaus.jettison.json.JSONObject.getJSONArray(JSONObject.java:436)
at playaround.FoursquareAPI.get(FoursquareAPI.java:56)
at playaround.FoursquareAPI.main(FoursquareAPI.java:31)

Code:

StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        for (String line; null != (line = reader.readLine());) {
            sb.append(line);
        }
        String output = sb.toString();
        JSONObject json = new JSONObject(output);
        JSONArray venues = json.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items");
        System.out.println(venues.length());

All I want is to read the response from Foursquare as JSONObject in Java. Any help?

Was it helpful?

Solution

Reading that stack trace, the JSON is being parsed just fine.

The problem is that you are trying to read a property that doesn't exist -- "groups"

OTHER TIPS

From my experience, if you get the JSON object - such as the problem I had ;parsing a returned LOCATION field. I started with the following code:

JSONObject jsonObjLoc = new JSONObject(myLocation);

If you can get the Object, then simply refer to "has" parameter like:

if(jsonObjLoc.has("myAddress")) { // name of field to look for 

           myTextAddress = jsonObjLoc.getString("address");
}

I use has to protect against the empty or null field not being returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top