在响应类型org.json.JSONObject时无法转换为JSONArray

问题描述 投票:0回答:1

我正在尝试使用HttpPost上传文件并将其发送到php,我会在JsonArray得到回复。但是,我遇到的问题是使用JsonArray或对象在Android应用程序中使用。然后,数组中的信息将被放入应用程序中的SQLite数据库中。我无法从数组中提取数据并收到以下错误

“在类型org.json.JSONObject的响应中无法转换为JSONArray”JSONArray arr = object.getJSONArray(“response”);

我对HttpPost不太熟悉,并且非常感谢我能得到的任何细节帮助。我从网上尝试过一些东西,但没有成功。

Array 
  ( 
     [response] => Array 
       ( 
           [Filepathserver] => webaddress 
           [email] => [email protected]
           [syncstatus] => yes 
       ) 

)  

java文件

   String url = "uploadphpfile.php";
    File file = new File(filepath);
    try {

        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(url);

         httppost.setEntity(mpEntity);
        Log.d("enitity",mpEntity.toString());

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity r_entity = response.getEntity();

       String result = EntityUtils.toString(r_entity);
        JSONObject object = new JSONObject(result);

        JSONArray arr =object.getJSONArray("response");

        for (int i = 0; i < arr.length(); i++) {
            JSONObject obj = arr.getJSONObject(i);
            Log.d("filepathserver",obj.get("Filepathserver").toString());
        }
        //Do something with response...
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            // Server response
          String  responseString = EntityUtils.toString(r_entity);
        } else {
            String responseString = "Error occurred! Http Status Code: "
                    + statusCode;
        }
     } catch (Exception e) {
          Log.e(DBHelperReports.class.getName(), e.getLocalizedMessage(), 
  e);
     }
    }

php文件

   $response = array();
  $response["Filepathserver"] = $target_path;
  $response["email"] = $target_path;
  $response["syncstatus"] = 'yes';
  echo json_encode(array("response"=>$response));

logcat的

  Value 
 {"Filepathserver":"webaddress","email":"[email protected]","syncstatus":"yes"} 
 at response of type org.json.JSONObject cannot be converted to JSONArray

 org.json.JSONException: Value 
 {"Filepathserver":"webaddress","email":"[email protected]","syncstatus":"yes"} 
 at response of type org.json.JSONObject cannot be converted to JSONArray

 at org.json.JSON.typeMismatch(JSON.java:100)

 at org.json.JSONObject.getJSONArray(JSONObject.java:588)

 at com.multiinspectionelite.DBHelperReports$1.run(DBHelperReports.java:383)

 at java.lang.Thread.run(Thread.java:762)
java php android json http-post
1个回答
3
投票

你的php文件产生了一个json对象,而不是一个json数组。

所以,试试JSONObject arr =object.getJSONObject("response");

顺便说一下,您的logcat已经提醒您将其视为JSONObject。

© www.soinside.com 2019 - 2024. All rights reserved.