通过PHP连接MySQL,JSON错误

时间:2011-12-05 01:16:29

标签: android

我写了一个simpe PHP脚本,打印出一个jsonencode($ output)。它输出带有前导和结尾[]的JSON。当我通过emulaotor运行我的Android程序时,它声明:JSONObject文本必须以[.....]的字符1开头,然后列出我的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;
}

}

1 个答案:

答案 0 :(得分:0)

听起来您的JSon响应如下:[{'name':'value'},...]

您的JSon对象必须以{开头,如错误消息所示。它应该是:
{'my_array':[.......]}

然后你可以写:new JSONObject().getJSONArray("my_array");