smartmouse
smartmouse

Reputation: 14404

How to handle JSON that contains strings with bracket?

I'm creating an activity that get a JSON file from internet (via AsyncTask). I'm experiencing this error: org.json.JSONException: Unterminated string at character...

I checked the JSON file that I downloaded inside the app and I discovered that there is an object that contains brackets. Here is the suspected JSON object:

[{ ... }{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"} { ... }]

So, how to escape the brackets from my activity?

Here is the part of AsyncTask in which I download the JSON file:

protected String doInBackground(String... urls) {
    int timeout = 10;
    int i, count = 0;

    BasicHttpParams basicParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(basicParams, timeout * 1000);
    HttpConnectionParams.setSoTimeout(basicParams, timeout * 1000 );
    DefaultHttpClient client = new DefaultHttpClient(basicParams);

    StringBuilder stringBuilder = new StringBuilder();
    for (i = 0; i < urls.length; i++) {
        HttpGet request = new HttpGet(urls[i]);
        request.addHeader("Cache-Control", "no-cache");

        try {
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            InputStreamReader in = new InputStreamReader(entity.getContent());
            BufferedReader reader = new BufferedReader(in);
            String line = "";

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);

                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        publishProgress(count * 100 / urls.length);
    }
    return stringBuilder.toString();
}

protected void onPostExecute(String result) {
    super.onPostExecute(result);

...
    JSONArray ja = new JSONArray(result);
...

Upvotes: 3

Views: 4127

Answers (1)

Swapnil Dey
Swapnil Dey

Reputation: 31

JSON response normally contains two kinds of brackets {} and [] but both the brackets have quite different meaning and use. While, the first one represents JSON Object, the second one represents JSON Array.

In the JSON file you downloaded, the problem has nothing to do with the [most] word as it is inside double quotes. The problem in your JSON input is "addr": "Main Street". The opening double quote is missing there.

Corrected JSON input:

{"id":"5674563646","cat":"Uncategorized","subcat":"Uncategorized","name":"Tecno Lab","desc":"We run open hours from 8-10pm and [most] Saturdays from 12-6pm.","addr":"Main Street","city":"New York","country":"United States"}

Upvotes: 1

Related Questions