我正在编写一个Android应用程序,它与Web服务交互以获取数据。 Web服务是用PHP编写的,我编写了一个使用AsyncTask来获取数据的库,问题是类只接受JSONObject。我的大多数服务只返回一个JSONObject,特别是返回一个json数组。
$array = array();
while ($row = mysql_fetch_array($query))
{
$array[] = $row;
}
echo json_encode($array);
返回如下内容:
[{ "0":"10","id":"10","1":"17.9409915","lat":"17.9409915","2":"-77.1003625","lon":"-77.1003625"},{"0":"9","id":"9","1":"17.9410143","lat":"17.9410143","2":"-77.1003672","lon":"-77.1003672"}]
我想要归还的是
{result:[{"0":"10","id":"10","1":"17.9409915","lat":"17.9409915","2":"-77.1003625","lon":"-77.1003625"},{"0":"9","id":"9","1":"17.9410143","lat":"17.9410143","2":"-77.1003672","lon":"-77.1003672"}]}
我试图通过以下方式实现这一目标:
echo json_encode("{result: " .$array. "}");
但这不起作用。它会回来。
"{result: Array}"
我该如何做到这一点?
答案 0 :(得分:4)
尝试
$array = array("result" => $array);
echo json_encode($array);
答案 1 :(得分:0)
您还可以使用JSONTokener将响应分派给正确的处理程序。
public void dispatchResponse(String response) {
JSONTokener tokener = new JSONTokener(response);
try {
Object object = tokener.nextValue();
if (object instanceof JSONObject) {
success(new JSONObject(response));
} else if (object instanceof JSONArray) {
success(new JSONArray(response));
} else {
// Etc...
}
} catch (JSONException e) {
Log.d("debug", "JSONException: "+ e.getMessage());
}
}
public void success(JSONObject response) {
Log.d("debug", "JSONObject: "+ response);
}
public void success(JSONArray response) {
Log.d("debug", "JSONArray: "+ response);
}