我从 mysql 数据库表中获取纬度和经度的值,其中两个字段数据类型都是双精度的,在 php 文件中我将这些值放在一个数组中并将它们作为对 json 的响应发送。我的 logcat 显示这些值是正确的,但它也说
“org.json.JSONArray 无法转换为 json 对象”
我在地图上看不到我想要的经纬度结果,但地图上还有其他地方。这是我的 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);
}
?>