2011-12-05 140 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