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

时间:2017-12-21 01:36:46

标签: java php android json http-post

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

  

"在响应类型为org.json.JSONObject时无法转换为   JSONArray" on JSONArray arr = object.getJSONArray(" response");

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

Array 
  ( 
     [response] => Array 
       ( 
           [Filepathserver] => webaddress 
           [email] => xyz@email.com
           [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":"xyz@email.com","syncstatus":"yes"} 
 at response of type org.json.JSONObject cannot be converted to JSONArray

 org.json.JSONException: Value 
 {"Filepathserver":"webaddress","email":"xyz@email.com","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)

1 个答案:

答案 0 :(得分:3)

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

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

顺便说一句,你的logcat已经提醒你把它当作JSONObject。