5

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

10
  • paste entire json here! or try to validate on www.jsonlint.com.I doubt there is some problem with json.
    – Vipul
    Jun 16, 2012 at 14:38
  • As I said (And I now validated again with jsonlint.com) it's a valid json... And the strange thing is, that it works on Android 4...
    – user754730
    Jun 16, 2012 at 14:42
  • Are you sure that the version of org.json library is the same on both devices? Also, increase your buffer size for your buffered reader.
    – wdziemia
    Jun 16, 2012 at 15:59
  • Yes I executed the exact same build on an emulator and devices running 2.1 and on my cell running 4.0.. Ok will try. But if it works on one why doesnt it on the other?
    – user754730
    Jun 16, 2012 at 16:07
  • what version of the SDK are you running?
    – wdziemia
    Jun 16, 2012 at 17:24

12 Answers 12

3
+25

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:

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);
    }
  }
}
4
  • Tried that but it gives the EXACT same file as I have on my server.
    – user754730
    Jun 19, 2012 at 10:09
  • @user754730: At this point, unless you can give us a project that reproduces the error, I doubt anyone can really help you. Jun 19, 2012 at 10:34
  • @user754730: Well, we certainly need the JSON that is causing the error. Jun 19, 2012 at 10:48
  • @user754730: I'll try to take a look at this sometime in the next 24 hours or so. Jun 19, 2012 at 11:39
2

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*/

1
  • Thanks alot for this approach! Unfortunately this does neither work on 2.1/2.2 not on 4.0 :(
    – user754730
    Jun 18, 2012 at 19:23
2

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.

2

I used following code for json, for me it support all android version.

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 !!");
}

I hope this will help you.

2

the solution here will solve your problem it's because of the utf-8 encoding coming back from the server.

JSON parsing problem

1

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

1
  • That's actually what I did have before. That doesn't work on either of the Versions :(
    – user754730
    Jun 19, 2012 at 10:12
1

Have you tried Jackson? I've used it on every version of android and it works quite nicely.

http://jackson.codehaus.org/

1

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

Some things I do notice:

  • InputStream is, String json, JSONObject jObj are declared externally to your getJSONFromUrl() method and there is a possibility that they are somehow affected differently by some other part of your code when running on one API compared to another.

  • Looking at the exception that you got, it is likely that it is thrown due to the fact that the input String to the JSONObject constructor is an empty string (""). Is it possible that somehow your server supplied a different data to your older Android?

Here's 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 debug code to print out the downloaded string between the last 2 try-catch blocks, like this:

    // ----- 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 know more about your issue after you make either one or both of the above changes :)

7
  • Thanks alot for your help! I did already have those 3 lines in my code before... I then tried the Logging stuff and it just prints out my complete JSON and then throws the exception as before :(
    – user754730
    Jun 19, 2012 at 22:36
  • 1
    Interesting, could you try calling your getJSONFromUrl(url) method passing http://pastebin.com/Jp6Z2wmX and http://pastebin.com/raw.php?i=Jp6Z2wmX as the url value? I would be very curious to see the logcat output from those two if you could put it on pastebin too.
    – Joe
    Jun 20, 2012 at 3:32
  • Wow strange enough it works from pastebin perfectly on 2.2 and 4.0. I have NO idea though why? So at the moment this is what the situation is like: Android 4 + our Server = WORKS, Android < 4 + our Server = DOESN'T WORK, Android 4 + Pastebin = WORKS, Android < 4 + Pastebin = WORKS
    – user754730
    Jun 20, 2012 at 15:16
  • Aha :) What server software do you use? I would look into the server logs and maybe even use Wireshark to see track it down at the lower level.
    – Joe
    Jun 20, 2012 at 17:53
  • Wow I still can't really believe it... We have a rented server which runs Apache. Maybe that's the problem? Or should I escape the strange characters (Like ö,ä,ü) from the JSON file?
    – user754730
    Jun 20, 2012 at 18:07
1

Have you tried the JSONParser?

here is a example wich i use:

   JSONObject json = new JSONObject();
   JSONParser jsonParser = new JSONParser(); 


    try {

        if(jsonString != null)
            json =  (JSONObject) jsonParser.parse(jsonString);

    } catch (ParseException e) {        
        e.printStackTrace();
    }
1

Jackson or GSON.

could be the german extra characters in there and an internationalization (i18n) or utf-8 issue.

I would restart Eclipse, do a clean build and try again.

4
  • 1
    Did that already.... Maybe escaping the extra characters could help?!
    – user754730
    Jun 22, 2012 at 6:42
  • escaping is a good idea or uuencoding/mime encoding/url encoding
    – Tim Spann
    Jun 23, 2012 at 10:45
  • Tried it... Didn't help either :(
    – user754730
    Jun 23, 2012 at 18:51
  • Restarting Eclipse to get an app work differently on a device? If that often solves issues for you, then I'm afraid your developer environment (and the way you build your apps) needs some proper set up.
    – Arjan
    Jun 24, 2012 at 15:20
1

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

Is it a String? If it is a JSONObject, change its type to String and your code will work perfectly.


Another remark is the handling of exceptions: It seems that if an exception is thrown in the first block when you building your String, the JSONObject initialization will be attempted with some faulty data.


Anyway try this (I suspect your download method is buggy):

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
  • Unfortunately this doesn't work either on Android 2.2... It does work on Android 4 though...
    – user754730
    Jun 26, 2012 at 9:41
0

Surely this will work. In 4.0 android version we have to create asynctask to avoid exception i.e NetworkOnMainThreadException ll get. Its working fine 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's 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..

Not the answer you're looking for? Browse other questions tagged or ask your own question.