繁体   English   中英

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

[英]Error parsing data.org.json.JSONException value of type java.lang.String cannot be converted to JSONArray

我使用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代码的一部分,results参数中的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!! 
    }

您尝试从array获取数组,但从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");          
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM