JSONArray无法转换为JSONObject

为什么JSONArray无法转换为JSONObject

这是我的java:

private fun findsend() {
    val URL_PROFILE = "https://awalspace.com/app/imbalopunyajangandiganggu/findsend.php"
    val stringRequest = object : StringRequest(Request.Method.GET,URL_PROFILE,Response.Listener { response ->
                try {
                    val jsonObject = JSONObject(response)
                    val jsonArray = jsonObject.getJSONArray("findsend")

                        for(i in 0 until jsonArray.length())
                        {
                            var `object` = jsonArray.getJSONObject(i)
                            var name = `object`.getString("name").trim()
                            var no_hp = `object`.getString("no_hp").trim()
                            fetchUsers(name,no_hp)
                        }


                } catch (e: JSONException) {
                    e.printStackTrace()
                    Toast.makeText(this,"Error $e",Toast.LENGTH_SHORT).show()
                }
            },Response.ErrorListener { error -> Toast.makeText(this,"Error $error",Toast.LENGTH_SHORT).show() }) {
    }
    val requestQueue = Volley.newRequestQueue(this)
    requestQueue.add(stringRequest)

}

这是我的JSON数据

JSON Data

mars00721 回答:JSONArray无法转换为JSONObject

尝试以下操作。

private fun findsend() {
    val URL_PROFILE = "https://awalspace.com/app/imbalopunyajangandiganggu/findsend.php"
    val stringRequest = object : StringRequest(Request.Method.GET,URL_PROFILE,Response.Listener { response ->
                try {
                    val jsonArray = JSONArray(response) // use JSONArray instead of JSONObject
                    for(i in 0 until jsonArray.length()){
                         var jsonObject = jsonArray.getJSONObject(i) // get each jsonobject from your jsonarray

                         var name = jsonObject.getString("name").trim()
                         var no_hp = jsonObject.getString("no_hp").trim()
                         fetchUsers(name,no_hp)
                    }


                } catch (e: JSONException) {
                    e.printStackTrace()
                    Toast.makeText(this,"Error $e",Toast.LENGTH_SHORT).show()
                }
            },Response.ErrorListener { error -> Toast.makeText(this,"Error $error",Toast.LENGTH_SHORT).show() }) {
    }
    val requestQueue = Volley.newRequestQueue(this)
    requestQueue.add(stringRequest)

}
本文链接:https://www.f2er.com/3162236.html

大家都在问