无法在android中使用JSONArray解析json
我想将 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 新手,所以也许这是一个愚蠢的问题,我只想知道未来的情况。感谢所有帮助发表评论的人。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至少我有明确的解决方案。
问题是我的php文件格式是带有BOM字符的utf-8。 BOM 给我带来了问题。我所要做的就是使用 Notepad++ 打开文件,然后选择 Codification->UTF-8 without BOM 并保存文件。
为了进一步简化,这里是我的 Android 代码的一个新的更短、更简单的版本:
仅此而已。
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:
That's all.