Android org.json.JSONException: Cannot convert to JSON array


Android org.json.JSONException: Cannot convert to JSON array

我得到org.json.JSONException:无法转换为JSON数组,这里的代码:

private String downloadUrl(String myurl) throws IOException {
     InputStream is = null;
     try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new     HttpPost("http://csddata.site11.com/json.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();
        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");
        }
        String read = sb.toString();    
        Log.d("HTTP", "Result = " + read);
        return read;    
     } finally {
         if (is != null) {
             is.close(); // Makes sure that the InputStream is closed after the app is// finished using it.
         } 
     }        

现在是我得到错误的代码:

 protected void onPostExecute(String result) {
        try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i); 
                MagList titleRow = new MagList();
                titleRow.title = json_data.getString("first_name");
                titleRow.page_url = json_data.getString("last_name");
                arrayOfWebData.add(titleRow);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Log.d("HTTP", "Error parsing data "+e.toString());
            Log.d("HTTP", "Failed data was:'n" + result);
            e.printStackTrace();
        } finally {}
        }

我同时收到"日志"。D",这是我从他们那里得到的:

05-24 16:44:59.721: D/HTTP(20260): Error parsing data org.json.JSONException: Value [
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"John" , "lastName":"Doe" }, 
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"Anna" , "lastName":"Smith" }, 
05-24 16:44:59.721: D/HTTP(20260): { "firstName":"Peter" , "lastName": "Jones" }
05-24 16:44:59.721: D/HTTP(20260): ]; of type java.lang.String cannot be converted to JSONArray 
05-24 16:44:59.721: D/HTTP(20260): Failed data was:
05-24 16:44:59.721: D/HTTP(20260): "['n{ '"firstName'":'"John'" , '"lastName'":'"Doe'" },<br> 'n{ '"firstName'":'"Anna'" , '"lastName'":'"Smith'" }, 'n{ '"firstName'":'"Peter'" , <br>'"lastName'": '"Jones'" }'n];"

有人能帮忙吗?如果你需要更多的信息,请留下评论:)

PHP文件:

<?php 
$json = '[
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName": "Jones" }
];';
print json_encode($json);
?>

修改后:

05-24 17:33:17.221: W/System.err(24203): org.json.JSONException: Value [
05-24 17:33:17.221: W/System.err(24203): {"firstName":"John","lastName":"Doe"}, 
05-24 17:33:17.221: W/System.err(24203): {"firstName":"Anna","lastName":"Smith"}, 
05-24 17:33:17.221: W/System.err(24203): {"firstName":"Peter","lastName": "Jones"}
05-24 17:33:17.221: W/System.err(24203): ] of type java.lang.String cannot be converted to JSONArray
05-24 17:33:17.221: W/System.err(24203):    at org.json.JSON.typeMismatch(JSON.java:111)
05-24 17:33:17.221: W/System.err(24203):    at org.json.JSONArray.<init>(JSONArray.java:91)
05-24 17:33:17.221: W/System.err(24203):    at org.json.JSONArray.<init>(JSONArray.java:103)
05-24 17:33:17.221: W/System.err(24203):    at com.example.android.navigationdrawerexample.MainActivity$DownloadWebpageTask.onPostExecute(MainActivity.java:381)
新代码:

// onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        try{
            if(result != null) result = result.replace("'n","");
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i); 
                MagList titleRow = new MagList();
                titleRow.title = json_data.getString("first_name");
                titleRow.page_url = json_data.getString("last_name");
                arrayOfWebData.add(titleRow);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Log.d("HTTP", "Error parsing data "+e.toString());
            Log.d("HTTP", "Failed data was:'n" + result);
            e.printStackTrace();
        } finally {}

        aa=new FancyAdapter();
        listV.setAdapter(aa);

   }
 // Given a URL, establishes an HttpUrlConnection and retrieves
 // the web page content as a InputStream, which it returns as
 // a string.
 private String downloadUrl(String myurl) throws IOException {
     InputStream is = null;
     try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://csddata.site11.com/json.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();
        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);
        }
        String read = sb.toString();    
        Log.d("HTTP", "Result = " + read);
        return read;    
     } finally {
         if (is != null) {
             is.close(); // Makes sure that the InputStream is closed after the app is// finished using it.
         } 
     }        
 }
}

我认为问题是你正在尝试json_encode一个字符串,已经json编码在你的php代码。通常在php数组上调用json_encode将其重新格式化为json字符串。因为它已经是一个字符串,我相信你可以简单地echo($json);,而不是试图json_encode它。

当前json字符串存在以下问题:

1。你需要在PHP代码中删除Json字符串中的空格,然后将其传递给json_encode。有效的json字符串是:

$json = '[
{"firstName":"John","lastName":"Doe"}, 
{"firstName":"Anna","lastName":"Smith"}, 
{"firstName":"Peter","lastName": "Jones"}
]';
print $json;

2。BufferedReader读取数据时不需要添加新的行字符:

String line = null;
while((line = reader.readLine()) != null){
  sb.append(line);  //<<< remove 'n from here
}

这是因为字符串中出现了新的行字符('n)。要么通过替换从字符串中删除它,要么不从服务中返回带有"'n"字符的响应。那么JSONArray就可以正常工作了。

编辑:do this:

try{
            if(result != null) result = result.replace("'n","");
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i); 
                MagList titleRow = new MagList();
                titleRow.title = json_data.getString("first_name");
                titleRow.page_url = json_data.getString("last_name");
                arrayOfWebData.add(titleRow);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Log.d("HTTP", "Error parsing data "+e.toString());
            Log.d("HTTP", "Failed data was:'n" + result);
            e.printStackTrace();
        } finally {}
        }

EDIT2:刚刚注意到你正在追加"'n"到你的字符串生成器。这就是误差点。另一个答案是正确的。不需要在字符串中执行replace

EDIT3:用以下代码替换。删除所有新行字符:

$json = '[{"firstName":"John","lastName":"Doe"},{"firstName":"Anna","lastName":"Smith"}, {"firstName":"Peter","lastName": "Jones"}]';
print json_encode($json);