0

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

3 回答 3

1

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

于 2013-05-24T16:43:38.867 回答
1

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

1.您需要从PHP代码中的Json String中删除空格,然后再将其传递给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
}
于 2013-05-24T16:23:40.680 回答
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);
于 2013-05-24T16:19:34.133 回答