【问题标题】:Cannot parse json with JSONArray in android无法在android中使用JSONArray解析json
【发布时间】:2011-04-12 09:40:59
【问题描述】:

我想将 json 字符串转换为 JSONArray,但它会抛出 jsonexception

这很奇怪,因为它给我的错误原因在调试后似乎完全错误。

这是代码的重要部分:

...

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

这是我在调试时得到的异常的详细信息:

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 处确实有一个 '['。我已经保证逐个位置地观察字符串。所以我不知道真正的错误在哪里。

你能帮帮我吗?我完全迷失在这里。提前致谢。

注意:现在我已经修剪了结果变量,我得到了同样的错误。这就是它的价值:

[{"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}]

临时解决方案和问题:

我已经解决了添加这一行的问题:

sb.deleteCharAt(0);

这里:

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

...

我不知道为什么,但我的回复在我的 StringBuilder 的位置 0 处添加了一个空字符(或类似的东西,因为修剪功能没有效果,但调试器也没有显示任何内容)。问题是异常消息令人困惑,并且在某种程度上说明了一些错误。

我在我的 php 文件中得到的响应是这样的:

<?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 新手,所以也许这是一个愚蠢的问题,我只是想知道未来的情况。感谢所有为您的 cmets 提供帮助的人。

【问题讨论】:

  • 您发布的 JSON 是有效的。我刚刚尝试在 Android 上用 JSONArray 解析它,它成功了。我会仔细检查字符串是否是您认为的字符串,并且开头或结尾没有任何多余的字符。
  • 按原样发布变量结果的值。修剪结果的值并检查。
  • 我已经完成了,但问题仍然存在。我已经编辑了帖子以向您展示变量的值。
  • 为什么要在文件的每一行读取一个新行字符?这会让我相信它实际上是在第 1 行添加一个 \n 的东西然后你的 JSON 字符串是无效的?
  • 我同意,+ "\n" 可能会产生不良影响。

标签: java android json parsing gson


【解决方案1】:

至少我有明确的解决方案。

问题是我的 php 文件格式是带有 BOM 字符的 utf-8。 BOM 给我带来了问题。我所要做的就是用我的 Notepad++ 打开文件,然后选择 Codification->UTF-8 without BOM 并保存文件。

为了进一步简化,这里是我的 Android 代码的一个新的更短、更简单的版本:

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

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多