Cannot parse json with JSONArray in android

2019-04-17 10:22发布

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.

1条回答
We Are One
2楼-- · 2019-04-17 10:45

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.

查看更多
登录 后发表回答