我在使用Java解析来自MySQL的JSON响应时遇到问题。
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://parkfinder.zxq.net/default.php");
httppost.setEntity(new UrlEncodedFormEntity(coordinatesToSend));
HttpResponse response = httpclient.execute(httppost);
Log.d("HTTP Client", "HTTP Request made");
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,
"iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(bufferedReader.readLine() + "\n");
String line = "0";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
bufferedReader.close();
result = sb.toString();
Log.d("RESULT", result);
JSONObject json_data = new JSONObject(result);
Log.d("JSON","Finished");
JSONArray nameArray = json_data.names();
JSONArray valArray = json_data.toJSONArray(nameArray);
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}
} catch (Exception e) {
// TODO: handle exception
}
这是MySQL访问和检索信息,并在事后解析它。 在
Log.d("RESULT", result);
发布正确的结果:
2[{"longtitude":"32.32","latitude":"33.12"}]
然而
Log.d("JSON","Finished");
永远不会被召唤, 所以问题似乎就在这一行
JSONObject json_data = new JSONObject(result);
这件事情是从一个教程中得到的,我在互联网和本网站上看到了很多这样的例子,一些陈述的错误,但不是这个。
任何帮助都会很棒! 感谢
编辑: printStackTrace()输出:
0`5-14 21:38:18.639: WARN/System.err(665): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of 2[{"longtitude":"32.32","latitude":"33.12"}]`
php代码:
<?php
$host = "localhost";
$user = "**MASKED**";
$password = "**MASKED**";
$database = "parkfinder_zxq_coordinates";
$connection = mysql_connect($host, $user, $password) or die("couldn't connect to server");
$db = mysql_select_db($database, $connection) or die("couldn't select database.");
//$request_parked = $_REQUEST['parked'];
$request_long = $_REQUEST['longtitude'];
$request_lat = $_REQUEST['latitude'];
//if ($request_parked == 'FIND') {
$q = mysql_query("SELECT * FROM Coordinates");
while ($e = mysql_fetch_assoc($q))
$output[] = $e;
print (json_encode($output));
//}
mysql_close();
?>
答案 0 :(得分:2)
您的JSON数据2[{"longtitude":"32.32","latitude":"33.12"}]
无效(数字2
不是正确的JSON语法)。
我可以建议你实际意味着
[{"longtitude":"32.32","latitude":"33.12"}]`
(即开头没有2
)
您可以使用http://jsonlint.com/处的验证程序检查您的JSON代码。