无法解析JSON与JSONArray在安卓 [英] Cannot parse json with JSONArray in android

查看:171
本文介绍了无法解析JSON与JSONArray在安卓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个 JSON 字符串转换为JSONArray,但它抛出一个 jsonexception

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.

这是的code中的重要组成部分:

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}]

正如你所看到的确有[人品1.我确信这个看根据位置的字符串的位置。所以我想不通的地方真正的错误是。

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}]

临时解决方案和问题:

我已经解决了这个问题,加入这一行:

I have solved the problem adding this line:

sb.deleteCharAt(0)

sb.deleteCharAt(0);

这里:

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

...

我不知道为什么,但我的回应添加一个空字符(或类似的东西,因为微调功能并没有影响,但在调试器还没有显示任何东西)在我的StringBuilder的位置0。问题是该异常信息是混乱的,并告诉一些莫名其妙erroneus。

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.

我不得不在我的PHP文件中获得响应是这样的:

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();
?>

我已经解决了这个问题了,但没有人知道为什么这个PHP会将此空字符我的反应(这也是在年底增加了它)?我是新来的PHP,所以也许这是一个愚蠢的问题,我只是想知道未来的情况。感谢大家谁帮助你的意见。

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.

推荐答案

至少我有明确的解决办法。

At least I have the definitive solution.

但问题是,我的PHP文件格式为UTF-8 BOM字符。 BOM表是什么给我的问题。我所要做的就是用我的Notepad ++打开该文件,并选择Codification-> UTF-8无BOM和保存文件。

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.

和这里进一步的简化是一种新的更短,更容易的版本我的Andr​​oid code:

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.

这篇关于无法解析JSON与JSONArray在安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆