0

I am getting this JSON string:

[
{
    "id": 135,
    "date": "2013-08-30 19:00:29",
    "timestamp": "2013-08-30 19:00:29",
    "lat": "54.328274",
    "long": "-2.747215",
    "strap": "annual International Festival of Street Arts",
    "link": "http://dev.website.co.uk//?p=135",
    "title": "Title"
}
]

Which is correct JSON syntax im sure (works fine in the iOS app), however when parsing to a JSONObject it catches an error. Java:

public static JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;   
    String result = "";   
    JSONObject jArray = null;

    //http post
    try {

        HttpClient httpclient = new DefaultHttpClient();   
        HttpPost httppost = new HttpPost(url);    
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        is = entity.getContent();    

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection "+e.toString());   
    }
    //convert response to string

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);  
        StringBuilder sb = new StringBuilder();   
        String line = null;

        while ((line = reader.readLine()) != null) {   
            sb.append(line + "\n");
        }

        is.close();
        result=sb.toString();

    } catch (Exception e) {    
        Log.e("log_tag", "Error converting result "+e.toString());
    }
    //try parse the string to a JSON object

    try {
        Log.d("log_tag", "jresult: " + result + "finish");
        jArray = new JSONObject(result);

    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return jArray;
}

Is there an error somewhere in the JSON?

3 Answers 3

4

[ represents a json array node

{ represents a json object node

    JSONArray jArray  = new JSONArray(result);
    return jArray;  

Also you can have one try block instead of many.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Best explanation here, so thank you! I will accept it when it allows :)
@JoshBoothe you are welcome. also you can have one try block and have many catch block based on exception hierarchy
0

It's an array, so you need to do "new JSONArray()" instead of "new JSONObject()".

Comments

0

when a json string starts with [ the it will be treated as a JSONArray you need to do new JSONArray()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.