Php 返回JSON对象而不是JSONArray

Php 返回JSON对象而不是JSONArray,php,android,json,Php,Android,Json,我正在编写一个android应用程序,它与web服务交互以获取数据。Web服务是用PHP编写的,我编写了一个库,它使用AsyncTask来获取数据。问题是类只接受JSONObject。我的大多数服务只返回一个JSONObject,因为有一个特定的服务返回一个json数组 $array = array(); while ($row = mysql_fetch_array($query)) { $array[] = $row; } echo j

我正在编写一个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}"
我怎样才能做到这一点呢?

试试看

$array = array("result" => $array);
echo json_encode($array);
试一试


您还可以使用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);
}

您还可以使用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);
}