JSON Parsing works on Android 4.0, but not on Android <4.0

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 versions of Android. This is part of my manifest:

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

And this is my syntax 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 older devices, the following error message appears (But, as I said, 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 works on Android 4, but not on older devices.

Find Json from here

+5
source share
12 answers

It is possible that the JSONObject parser JSONObject become softer in newer versions of Android. The error message you get seems to be related to questionable JSON, especially on the receiving side:

I would advise you to write the downloaded JSON to a file and compare it with your original to see if there is a problem with the loading logic.


UPDATE

I can not reproduce your problem. Downloading JSON from external storage works 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 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); } } } 
+3
source

Usually these are the next steps to create a json object via an http connection in android.

  • open the connection and get a response.
  • Get the contents and create a row builder.
  • turn the string builder into a json array object (you have not done this step yet)
  • Get json object from json array object.

I think you missed the conversion of String Buffer (sb) to a json array object. Instead, you directly create a json object from the string buffer. I do not know how it worked in android 4.0. Modified 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 { 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 the index value, e.g.

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

+2
source

Hello, I used the following code, and I did not get any errors in 2.2, 2.3.3 the 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 this helps.

+2
source

I used the following code for json, for me it supports the whole version of Android.

 List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("data", qry)); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); HttpPost request = new HttpPost(your url); request.setEntity(formEntity); HttpResponse rp = hc.execute(request); Log.d("UkootLog", "Http status code " + rp.getStatusLine().getStatusCode()); if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK || rp.getStatusLine().getStatusCode() >= 600) { Log.d("JsonLog", "Success !!"); String result = EntityUtils.toString(rp.getEntity()); } else { Log.d("UkootLog", "Failed while request json !!"); } 

Hope this helps you.

+2
source

the solution here will solve your problem this is because of utf-8 encoding coming back from the server.

JSON parsing issue

+2
source

I am not very sure why you are getting this error. But I also ran into a similar problem, and it was solved by changing the charSet. Try using iso-8859-1 instead of UTF-8 .

+1
source

Have you tried Jackson? I used it for every version of Android, and it works very well.

http://jackson.codehaus.org/

+1
source

Have you tried JSONParser?

here is the example i am using:

  JSONObject json = new JSONObject(); JSONParser jsonParser = new JSONParser(); try { if(jsonString != null) json = (JSONObject) jsonParser.parse(jsonString); } catch (ParseException e) { e.printStackTrace(); } 
+1
source

I copied your code and used http://pastebin.com/raw.php?i=Jp6Z2wmX as input to your getJSONFromUrl(String url) method. Interestingly, I was not able to reproduce your problem (with several combinations of AVD and / or target API 15, 10 or 7).

Some things I notice:

  • InputStream is , String json , JSONObject jObj are declared externally by your getJSONFromUrl() method, and there is a chance that they will be affected in some way by some other part of your code when working on one API compared to another.

  • Looking at the exception you received, it is likely that it was JSONObject because the String input in the JSONObject constructor is an empty string (""). Is it possible that somehow your server provided other data to your older Android?

Here are my suggestions:

  • Add the following lines to the top of your getJSONFromUrl() method:

     InputStream is = null; String json = null; JSONObject jObj = null; 
  • Add a line of debugging code to print the loaded line between the last two try-catch blocks, for example:

     // ----- cut ---- Log.e("Buffer Error", "Error converting result " + e.toString()); } Log.d("getJSONFromUrl", "json=(" + json + ")"); try { jObj = new JSONObject(json); // ----- cut ---- 

I think we will learn more about your problem after you make one or both of the above changes :)

+1
source

Jackson or GSON.

may be German extra characters and internationalization issue (i18n) or utf-8.

I restarted Eclipse, make a clean build, and try again.

+1
source

What is the type of the variable named json in the string: json = sb.toString();

Is this a string? If it's a JSONObject , change its type to String and your code will work fine.


Another point is exception handling. It seems that if an exception is thrown in the first block when you build your String, JSONObject initialization will try with some erroneous data.


In any case, try this (I suspect your boot method is not working):

 public JSONObject getJSONFromUrl(String url) { try { HttpPost postMethod = new HttpPost(SERVER_URL); ResponseHandler<String> res = new BasicResponseHandler(); ResponseHandler<String> res = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException( statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity, "UTF-8"); } }; String response = (new DefaultHttpClient()).execute(postMethod, res); return new JSONObject(json); } catch (Exception e) { e.printStackTrace(); return null; } } 
+1
source

Of course it will work. In version 4.0 for Android, we must create asynctask to avoid the ie NetworkOnMainThreadException ll get exception. His work is wonderful for me.

 public class Http_Get_JsonActivity extends Activity implements OnClickListener { String d = new Date().toString(); private static final String TAG = "MyPost"; private boolean post_is_running = false; private doSomethingDelayed doSth; private String url = "http://192.168.1.1"; private InputStream is; private String json; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button pushButton = (Button) findViewById(R.id.button1); pushButton.setOnClickListener(this); } @Override protected void onPause() { super.onPause(); if (post_is_running) { // stop async task if it running if app gets // paused Log.v(TAG, "Stopping Async Task onPause"); doSth.cancel(true); } } @Override protected void onResume() { super.onResume(); if (post_is_running) { // start async task if it was running previously and was stopped by // onPause() Log.v(TAG, "Starting Async Task onResume"); doSth = (doSomethingDelayed) new doSomethingDelayed().execute(); // ((Button) findViewById(R.id.push_button)).setText("Resuming.."); } } public void onClick(View v) { if (post_is_running == false) { post_is_running = true; Log.v(TAG, "Starting Async Task onClick"); doSth = (doSomethingDelayed) new doSomethingDelayed().execute(); // ((Button) findViewById(R.id.push_button)).setText("Starting.."); } else { Log.v(TAG, "Stopping Async Task onClick"); post_is_running = false; doSth.cancel(true); // ((Button) findViewById(R.id.push_button)).setText("Stopping.."); } } private class doSomethingDelayed extends AsyncTask<Void, Integer, Void> { private int num_runs = 0; @Override protected Void doInBackground(Void... gurk) { // while (!this.isCancelled()) { Log.v(TAG, "going into postData"); long ms_before = SystemClock.uptimeMillis(); Log.v(TAG, "Time Now is " + ms_before); postData(); Log.v(TAG, "coming out of postData"); publishProgress(num_runs); return null; } @Override protected void onCancelled() { Context context = getApplicationContext(); CharSequence text = "Cancelled BG-Thread"; int duration = Toast.LENGTH_LONG; Toast.makeText(context, text, duration).show(); } @Override protected void onProgressUpdate(Integer... num_runs) { Context context = getApplicationContext(); } } /** * Method to send data to the server */ public void postData() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(url); System.out.println("--httppost----" + httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); System.out.println("--httpResponse----" + httpResponse); HttpEntity httpEntity = httpResponse.getEntity(); System.out.println("--httpEntity----" + httpEntity); is = httpEntity.getContent(); System.out.println("--is----" + is); } 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); System.out.println("--jObjt--" + jObj); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } } } 

enjoy..

0
source

Source: https://habr.com/ru/post/946666/


All Articles