Josh Boothe
Josh Boothe

Reputation: 1423

JSONObject not being correctly created (possible JSON formatting error?)

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?

Upvotes: 0

Views: 1185

Answers (3)

nsfyn55
nsfyn55

Reputation: 15363

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

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

[ 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.

Upvotes: 4

faffaffaff
faffaffaff

Reputation: 3549

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

Upvotes: 0

Related Questions