Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parsing works on Android 4.0 but not on Android < 4.0 [duplicate]

Possible Duplicate:
JSON parsing problem

I am parsing a JSON file (Which is valid). It works on Android 4.0 - 4.0.4 but not on older Android versions. This is a part of my Manifest:

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="14" />

And this is my parsing code:

public JSONObject getJSONFromUrl(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;

}

And on the older devices I get the following error message (But as I said not on new Android devices):

org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject

I have absolutely no idea why it does work on Android 4 but not on older devices.

Find the Json from here

like image 576
user754730 Avatar asked Jun 16 '12 14:06

user754730


People also ask

Why does JSON parse not work?

JSON. parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code. If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands.

Which Library in Android will used for JSON parsing?

Android JSONObject is used for JSON parsing in android apps.

What is parsing in Android explain JSON parsing with suitable example?

Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and all other forms to parse the JSON data and fetch the required information by the program. JSON's main advantage is that it is a language-independent, and the JSON object will contain data like a key/value pair.

What are the JSON element in Android?

Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer. The first step is to identify the fields in the JSON data in which you are interested in. For example.


3 Answers

It is possible that the JSONObject parser has been made more lenient in newer Android releases. The error message you are getting appears to be due to dubiously-legal JSON, particularly on the receiving side:

  • Issue initializing a JSONObject
  • JSON parsing problem

I would suggest that you write your downloaded JSON out to a file and compare it with your original to see if there is a problem with the download logic.


UPDATE

I cannot reproduce your problem. Loading that JSON off of external storage works perfectly fine on Android 4.0.3., 2.3.3, 2.2, and 2.1, using the following activity (note: I was lazy and hard-wired in the path to external storage):

package com.commonsware.jsontest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTestActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try {
      BufferedReader in=
          new BufferedReader(new FileReader("/mnt/sdcard/test.json"));
      String str;
      StringBuilder buf=new StringBuilder();

      while ((str=in.readLine()) != null) {
        buf.append(str);
        buf.append("\n");
      }

      in.close();
      JSONObject json=new JSONObject(buf.toString());

      ((TextView)findViewById(R.id.stuff)).setText(json.toString());
    }
    catch (IOException e) {
      Log.e(getClass().getSimpleName(), "Exception loading file", e);
    }
    catch (JSONException e) {
      Log.e(getClass().getSimpleName(), "Exception parsing file", e);
    }
  }
}
like image 108
CommonsWare Avatar answered Oct 22 '22 12:10

CommonsWare


Usually these are the following steps to create json object through the Http connection in android.

  1. open the connection and get the response.
  2. get the content and create a string builder.
  3. make the string builder into json array object (this step you have not done)
  4. get json object from the json array object.

I think you missed to convert String Buffer(sb) into json array object. Instead of that you directly create the json object from string buffer. I dont know how its was worked in android 4.0. The modified code is

public JSONObject getJSONFromUrl(String url) {
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
       JSONArray jObj = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;

}

And you can get the json object by passing index value like,

jObj.getJSONObject(i); /*i is a integer, index value*/

like image 2
Akilan Avatar answered Oct 22 '22 13:10

Akilan


Hello i used the following code and i did not get any errors in 2.2, 2.3.3 code is very simple.

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class NannuExpActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            JSONObject jo = getJSONObjectFromUrl("http://pastebin.com/raw.php?i=Jp6Z2wmX");
            for(int i=0;i<jo.getJSONArray("map_locations").length();i++)
            Log.d("Data",jo.getJSONArray("map_locations").getJSONObject(i).getString("title"));
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    public JSONObject getJSONObjectFromUrl(String url) throws ClientProtocolException, IOException, JSONException{
        JSONObject jobj = null;
        HttpClient hc = new DefaultHttpClient();
        HttpGet hGet = new HttpGet(url);
        ResponseHandler<String> rHand = new BasicResponseHandler();
        String resp = "";
        resp = hc.execute(hGet,rHand);
        jobj = new JSONObject(resp);    
        return jobj;
    }
}

Hope it helps.

like image 2
Raghav Avatar answered Oct 22 '22 12:10

Raghav