0

我正在编写一个与 Web 服务交互以获取数据的 android 应用程序。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}"

我怎样才能做到这一点?

4

2 回答 2

4

尝试

$array = array("result" => $array);
echo json_encode($array);
于 2013-05-06T17:09:21.580 回答
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);
}
于 2013-05-06T18:22:20.607 回答