【问题标题】:The JSONArray cannot be converted to JSONObjectJSONArray 无法转换为 JSONObject
【发布时间】:2019-11-05 04:44:07
【问题描述】:

为什么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

【问题讨论】:

  • json 数组和 json 对象是两个不同的东西
  • 是的,如果我只有 1 个数组,我可以将其转换为对象。但我在那边带了很多数组
  • 应该是val jsonArray = JSONArray(response),因为你的响应是一个数组。
  • 您只有 1 个带有多个 json 对象的 json 数组。检查我在上面分享的链接

标签: android json kotlin


【解决方案1】:

尝试如下。

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)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多