0

I want to convert a json string to a JSONArray but it throws a jsonexception

It's very strange because the error cause it gives to me seems totally false having debugged.

this is the important part of the code:

...

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// convert response to string
try {
        BufferedReader reader = new BufferedReader(
    new InputStreamReader(is, "utf-8"));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
          sb.append(line + "\n");
    }
    is.close();

        String result = sb.toString();
        result.trim(); //added by recommendation in comments                

        // parse json data
    try {
        JSONArray jArray = new JSONArray(result); **//this line jumps to the exception**
            //Also tried
            //JSONTokener tokener = new JSONTokener(result);
            //JSONArray jArray = new JSONArray(tokener); //jumps to the exception too

                for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
            TextView info = (TextView)findViewById(R.id.info);
            String sInfo = "id: "
                + json_data.getInt("ID")
                + ", descripció: "
                + json_data.getString("DESC")
                + ", nick: "
                + json_data.getString("NICK")
                + ", data de naixement: "
                + json_data.getString("DATA_NEIX");
                    info.setText(sInfo);
                }
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data "
                    + e.toString());
                }

This is the detail message of the exception i get when debugging:

A JSONArray text must start with '[' at character 1 of [{"ID":"1","NICK":"Jauuu","DESC":"Estic de proves amb php i mysql","FOTO":null,"DATA_NEIX":"1980-04-22","IDIOMA":null,"PAIS":"Espanya","GENERE":"H","ORIENTACIO":"heterosexu","ID_GRUP":null,"ESTAT":null,"ID_AMICS":null}]

As you can see there is indeed a '[' at character 1. I have assured this watching the string position by position. So I can't figure where the real error is.

Please can you help me? I'm totally lost here. Thanks in advance.

Note: Now I have trimmed the result variable and i get the same error. Here it is it's value:

[{"ID":"1","NICK":"Jauuu","DESC":"Estic de proves amb php i mysql","FOTO":null,"DATA_NEIX":"1980-04-22","IDIOMA":null,"PAIS":"Espanya","GENERE":"H","ORIENTACIO":"heterosexu","ID_GRUP":null,"ESTAT":null,"ID_AMICS":null}]

Provisional solution and questions:

I have solved the problem adding this line:

sb.deleteCharAt(0);

here:

...
sb.deleteCharAt(0);
String result = sb.toString();
result.trim();

...

I don't know why, but my response added an empty character (or something like that, because the trim function didn't had effect but the debugger also didn't show anything) at position 0 of my StringBuilder. The problem was that the exception message was confusing and telling something somehow erroneus.

All i had in my php file to get the response was this:

<?php
mysql_connect("127.0.0.1","root","");
mysql_select_db("prova");

$q=mysql_query("SELECT * FROM perfil WHERE ID='".$_REQUEST['id']."'");
while($e=mysql_fetch_assoc($q))
        $output[]=$e;

print(utf8_encode(json_encode($output)));

mysql_close();
?>

I have solved the problem now, but does anyone know why this php adds this empty character to my response (it also adds it at the end)?. I'm new to php, so perhaps it's a dumb question, i just want to know for future cases. Thanks to all of you who have helped with your comments.

12
  • The JSON you posted is valid. I just tried parsing it in a JSONArray on Android and it worked. I would double-check the string is what you think it is, and doesn't have any extra characters on the beginning or end. Commented Apr 12, 2011 at 9:54
  • post the value of variable result as it is. Trim the value of result and check. Commented Apr 12, 2011 at 9:59
  • I've done it but there is still the problem. I've edited the post to show you the value of the variable. Commented Apr 12, 2011 at 10:30
  • Why append a new line character to the string at each read line of the file? That would lead me to believe it is, in fact, getting something on line 1 appending a \n and your JSON string is then invalid? Commented Apr 12, 2011 at 10:37
  • I agree, the + "\n" may have unwanted effects. Commented Apr 12, 2011 at 10:38

1 Answer 1

2

At least I have the definitive solution.

The problem was that my php file format is utf-8 with BOM character. The BOM is what was giving me problems. All I have to do is open the file with my Notepad++ and select Codification->UTF-8 without BOM and save the file.

And for further simplification here is a new shorter and easier version of my Android code:

try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2:8888/obtePerfil.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    //this line here is what saves a lot of work
    String result = EntityUtils.toString(entity, HTTP.UTF_8);

    // parse json data
    try {
        JSONArray jArray = new JSONArray(result);                           
        for (int i = 0; i < jArray.length(); i++) {
        JSONObject json_data = jArray.getJSONObject(i);
        TextView info = (TextView) findViewById(R.id.info);
        String sInfo = "id: " + json_data.getInt("ID")
                + ", descripció: "
                + json_data.getString("DESC") + ", nick: "
                + json_data.getString("NICK")
                + ", data de naixement: "
                + json_data.getString("DATA_NEIX");
        info.setText(sInfo);
        }
    } catch (Exception e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
        }
} catch (Exception e) {
        Log.e("log_tag", "Error in http connection "+ e.toString());
        }

That's all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.