2011-12-05 44 views
0

我寫了一個簡單的PHP腳本,打印一個jsonencode($ output)。它輸出帶有前導和結尾[]的JSON。當我通過emulaotor運行Android程序時,它指出:JSONObject文本必須以[{'字符1開頭,然後列出我的JSON,因此我知道它獲取數據,解碼過程中不去除那些方括號。下面是引發錯誤的日誌功能:通過PHP連接MySQL,JSON錯誤

public class JSONfunctions { 

public static JSONObject getJSONfromURL(String url){ 
    InputStream is = null; 
    String result = ""; 
    JSONObject jArray = null; 

    //http post 
    try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 

    }catch(Exception e){ 
      Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 

    //convert response to string 
    try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
      } 
      is.close(); 
      result=sb.toString(); 
    }catch(Exception e){ 
      Log.e("log_tag", "Error converting result "+e.toString()); 
    } 

    try{ 

     jArray = new JSONObject(result);    
    }catch(JSONException e){ 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
    } 

    return jArray; 
} 

}

回答

0

這聽起來像你的JSON響應的樣子:[{'name':'value'},...]

你的JSON對象必須{開始像錯誤信息說。它應該是:
{'my_array':[.......]}

然後,你可以寫:new JSONObject().getJSONArray("my_array");

+0

但默認打印(jsonencode($輸出));來自PHP的格式不帶標題和方括號。沒辦法改變這一點。 – savagenoob