我想将 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 处确实有一个 '['
。我保证这一点逐个位置地观察字符串。所以我无法弄清楚真正的错误在哪里。
请问你能帮我吗?我完全迷失在这里了。提前致谢。
注意:现在我已经修剪了结果变量,但出现了相同的错误。这就是它的值(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}]
临时解决方案和问题:
我已经解决了添加此行的问题:
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 新手,所以也许这是一个愚蠢的问题,我只想知道 future 的情况。感谢所有帮助发表评论的人。
最佳答案
至少我有明确的解决方案。
问题是我的php文件格式是带有BOM字符的utf-8。 BOM 给我带来了问题。我所要做的就是使用 Notepad++ 打开该文件,然后选择“编码”->“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());
}
仅此而已。
关于java - 无法在android中使用JSONArray解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5633212/