Android org.json.JSONException:无法转换为JSON数组

时间:2013-05-24 16:11:58

标签: php android json http

我收到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 {}
        }

我收到两个“Log.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.
         } 
     }        
 }
}

3 个答案:

答案 0 :(得分:1)

您在当前的json字符串中遇到以下问题:

1。在将代码传递给json_encode之前,您需要在PHP代码中删除Json String中的空格。有效的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
}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这是因为字符串中的新行字符(\ n)。通过替换字符串将其删除,或者不从服务中返回带有“\ n”字符的响应。 JSONArray可以正常工作。

编辑:执行此操作:

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”附加到字符串生成器。这是错误点。另一个答案是爆炸。无需在字符串中替换。

EDIT3: 替换为以下代码。删除所有新行号:

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