2013-05-06 204 views
0

我正在編寫一個android應用程序,它與Web服務進行交互以獲取數據。 Web服務使用PHP編寫,我寫了一個使用AsyncTask獲取數據的庫,問題在於類只接受JSONObject。我的大多數服務都只返回一個JSONObject,有一個返回一個json數組。返回JSON對象而不是JSONArray

$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

嘗試

$array = array("result" => $array); 
echo json_encode($array); 
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); 
} 
相關問題