尝试从MySQL查询解析JSON时出现java异常
我在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();
?>
# 1 楼答案
您的JSON数据
2[{"longtitude":"32.32","latitude":"33.12"}]
无效(数字2
不是正确的JSON语法)我能建议你是说
(也就是说,开头没有
2
)您可以使用位于http://jsonlint.com/的验证器检查JSON代码