gpt4 book ai didi

java - org.json.JSONObject 类型的响应无法转换为 JSONArray

转载 作者:行者123 更新时间:2023-12-01 20:02:05 24 4
gpt4 key购买 nike

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

"at response of type org.json.JSONObject cannot be converted to 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));

日志猫

  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)

最佳答案

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

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

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

关于java - org.json.JSONObject 类型的响应无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com