我从mysql数据库表中获取纬度和经度的值,其中两个字段的数据类型都是double,在php文件中,我将这些值放入一个数组中,并将它们作为对json的响应发送。我的日志显示这些值是正确的,但它也表明
“org.json.JSONArray无法转换为json对象”
我在地图上看不到我想从lat和long得到的结果,但地图上还有其他地方。这是我的java代码部分,它从php获取值。所以我如何处理这个转换来获得这些来自php的值,这样我就可以看到数据库中存储的位置。
JSONObject json_user1 = new JSONObject(responseFromPHP);
JSONObject json_user2 = json_user1.getJSONObject("latlong");
double latitude=Double.parseDouble((json_user2.getString(TAG_LATITUDE)));
double longitude=Double.parseDouble((json_user2.getString(TAG_LONGITUDE)));
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker Lahore = map.addMarker(new MarkerOptions().position(
new LatLng(latitude, longitude))
.title("Lahore"));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
日志:
10-10 22:49:47.655: D/Show lat n long:(30670): {"success":1,"latlongs":[{"longitude":"74.3436","latitude":"31.5497"}]}
10-10 22:49:47.655: W/System.err(30670): org.json.JSONException: Value [{"longitude":"74.3436","latitude":"31.5497"}] at latlongs of type org.json.JSONArray cannot be converted to JSONObject
10-10 22:49:47.660: W/System.err(30670): at org.json.JSON.typeMismatch(JSON.java:100)
10-10 22:49:47.660: W/System.err(30670): at org.json.JSONObject.getJSONObject(JSONObject.java:573)
10-10 22:49:47.660: W/System.err(30670): at com.DRMS.disas_recovery.MainActivity$LoadMap.onPostExecute(MainActivity.java:80)
10-10 22:49:47.660: W/System.err(30670): at com.DRMS.disas_recovery.MainActivity$LoadMap.onPostExecute(MainActivity.java:1)
10-10 22:49:47.665: W/System.err(30670): at android.os.Handler.dispatchMessage(Handler.java:99)
PHP代码:
<?php
$response = array();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$result = mysql_query("SELECT latitude, longitude FROM tbl_map WHERE map_id=1") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$response["latlongs"] = array();
while ($row = mysql_fetch_array($result)) {
$latlong = array();
$latlong["latitude"] = $row["latitude"];
$latlong["longitude"] = $row["longitude"];
array_push($response["latlongs"], $latlong);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "Error nothing found";
// echo no users JSON
echo json_encode($response);
}
?>
最佳答案
你的问题在这里
JSONObject json_user2 = json_user1.getJSONObject("latlong");
json_user1.get("latlong")
是一个JSONArray
而不是JSONObject
。因为字符串以a[
开头,而不是a{
开头,这两个值分别对应于Array
和Object
。试试下面的。
JSONArray json_user2 = json_user1.getJSONArray("latlong");
那对你应该没问题。