gpt4 book ai didi

java - 解析 java.lang.String 类型的 data.org.json.JSONException 值时出错,无法转换为 JSONArray

转载 作者:行者123 更新时间:2023-12-01 13:55:17 27 4
gpt4 key购买 nike

我使用 php-mysql 和 json 收到此错误,说真的,我已经花了 2 天了,所以这是我的代码

require "includes/connexion.php";
$requete="SELECT * FROM contacts;";
$rep=$pdo->query($requete);

while($data=$rep->fetch(PDO::FETCH_ASSOC)){
$sortie[]=$data;
}
print(json_encode($sortie));
$rep->closeCursor();

这是 java 代码的一部分,结果参数中的 jsonArray 包含该值(来自控制台):

 [{"id":"1","nom":"Fedson Dorvilme","email":"fedsondorvilme@gmail.com","phone":"34978238","img":"ic_launcher"},{"id":"2","nom":"Darlene Aurelien","email":"darleneaurelien@yahoo.fr","phone":"34171191","img":"ic_launcher"}]



JSONArray array = new JSONArray(result);


for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i);

Log.i("MyLogFlag", "Nom Contact: " + json_data.getString("nom"));
returnString = "\n\t" + array.getJSONArray(i);
System.out.println(" ********** RS [ "+returnString+" ]****************");

}
} catch (Exception e) {
Log.e("log_Exception_tag", "Error parsing data " + e.toString());

}

提前感谢您的帮助

最佳答案

这是你的 json 结构:

[
{
"id": "1",
"nom": "Fedson Dorvilme",
"email": "fedsondorvilme@gmail.com",
"phone": "34978238",
"img": "ic_launcher"
},
{
"id": "2",
"nom": "Darlene Aurelien",
"email": "darleneaurelien@yahoo.fr",
"phone": "34171191",
"img": "ic_launcher"
}
]

来自您的 Java 代码:

JSONArray array = new JSONArray(result);  // OK


for (int i = 0; i < array.length(); i++) {
JSONObject json_data = array.getJSONObject(i); // OK

returnString = "\n\t" + array.getJSONArray(i); // ??? wrong!!
}

您尝试从数组获取数组,但它是 JSONObject

正确方法:

   JSONArray gb = new JSONArray(str);

for (int j = 0; j < gb.length(); j++) {
JSONObject element = gb.getJSONObject(j);

int id = element.getInt("id");
int phone = element.getInt("phone");
String nom = element.getString("nom");
String email = element.getString("email");
String img = element.getString("img");
}

关于java - 解析 java.lang.String 类型的 data.org.json.JSONException 值时出错,无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19663579/

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