3

好的,我知道以前有人问过这个问题,但是所有的答案都没有帮助。首先,让我回顾一下问题:

我有一个(PHP 生成的)JSON 元素,PHP 代码如下所示:

if (!headers_sent()) header('Content-type: application/json');
echo "[{\"test\":\"success\"}]";

在此之前没有其他回声,打印或其他任何东西,所以输出真的只是

[{"test":"success"}]

没有别的了。PHP 文件保存为纯 UTF-8(经过检查和双重检查)。

现在,我的 Android 代码如下所示:

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://myurl");
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"), 8);
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String menuData = builder.getString();

    ArrayList<HashMap<String, String>> tempList = new ArrayList<HashMap<String, String>>();
boolean change = false;

try {
    JSONArray jsonMenu = new JSONArray(menuData);

    for (int i = 0; i < jsonMenu.length(); i++) {
        JSONObject jsonObject;
        try {
            jsonObject = jsonMenu.getJSONObject(i);

            HashMap<String, String> menuItem = new HashMap<String, String>();
            menuItem.put("test", jsonObject.getString("test"));
            tempList.add(menuItem);
            change = true;

        } catch (JSONException e) {
        }
    }

} catch (JSONException e) {
}

if(change) {
     // here comes the listview update, but never triggered anyways
}

而且我总是收到相同的错误消息:

04-05 21:06:31.226: W/System.err(1208): org.json.JSONException: A JSONArray text must start with '[' at character 1 of ?[{"test":"success"}]

这其实是Logcat输出保存到log.txt并在这里解析,然后一下子就出现了这个问号。在将字符串解析为 JSONArray 之前对字符串进行修剪或格式化的所有尝试都失败了。我完全不知道还能做什么。顺便说一下,在 Eclipse 本身的 Logcat 中没有问号......

在 catch 语句中添加 Log.e 输出,错误输出完全相同。截图在这里:

LogCat 中的错误消息

4

1 回答 1

3

问题解决了:

在 Notepad++ 中打开 PHP 文件,点击 Encoding => Encode in UTF-8 without BOM。

我忽略了这一点,因为它在状态栏中显示“ANSI as UTF-8”,这听起来很不对(我想要纯 UTF-8 而没有 ANSI 混合)。是的,我不是 Linux 的家伙,所以这个 ANSI/UTF-8 是我从来没有得到说实话的东西,它又把我困住了。

如果有人对我如何找到解决方案感兴趣(这里归功于@Perception、@Raghav-Sood 和@Reuben-Scratton):

将 menuData 字符串转换为字节数组,发现前两个字符不是 JSONArray 要查找的左括号,而是两个 BOM 字符。

于 2013-04-06T12:16:15.743 回答