【问题标题】:Android Kotlin Volley How to send JSON DataAndroid Kotlin Volley 如何发送 JSON 数据
【发布时间】:2021-11-05 22:35:29
【问题描述】:

我想使用 Volley 将 JSON 有效负载发送到 REST API。但我得到一个错误

“com.android.volley.ParseError: org.json.JSONException: org.json.JSONArray 类型的值 [] 无法转换为 JSONObject”

来自 Magento 的有效负载 https://devdocs.magento.com/guides/v2.4/rest/tutorials/inventory/create-cart-add-products.html

JSON 负载

{
  "cartItem": {
    "sku": "10-1001",
    "qty": 5,
    "quote_id": "3"
  }
}

排球代码

// Create JSON
val itemsObject = JSONObject()
itemsObject.put("sku", "10-1001")
itemsObject.put("qty", 5)
itemsObject.put("quote_id", "3")

val itemsArray = JSONObject()
itemsArray.put("cartItem", itemsObject)


val jsonRequest = object : JsonObjectRequest(
        Request.Method.POST, url, itemsArray,

        Response.Listener { response ->

            try {

                binding.txtStatus.text = response.toString()

            } catch (e: JSONException) {
                e.printStackTrace()
                binding.txtStatus.text = e.toString()
            }

        },

        Response.ErrorListener { error ->

            binding.txtStatus.text = error.toString()

        }) {
        @Throws(AuthFailureError::class)
        override fun getBodyContentType(): String {
            return "application/json"
        }

        override fun getHeaders(): Map<String, String> {
            val apiHeader = HashMap<String, String>()
            apiHeader["Authorization"] = "Bearer $cusToken"
            return apiHeader
        }

    }

    val queue = Volley.newRequestQueue(this@MainActivity)
    queue.add(jsonRequest)

【问题讨论】:

    标签: android json rest kotlin android-volley


    【解决方案1】:

    您应该使用JSONArray 而不是JSONObject。你的itemsArray 必须是这样的:

    val itemsArray = JSONArray()

    您的请求负载必须如下所示,并且可以有多个对象:

    [
       {
          "sku":"10-1001",
          "qty":5,
          "quote_id":"3"
       },
       {
          "sku":"10-1002",
          "qty":1,
          "quote_id":"2"
       }
    ]
    

    原因是负载现在包含多个项目。您可以在JSONArray 中添加多个JSONObject

    另一种方法是,如果您想在请求有效负载中发送一些其他信息,那么您可能需要以下列方式使用:

    {
       "cartItems":[
          {
             "sku":"10-1001",
             "qty":5,
             "quote_id":"3"
          },
          {
             "sku":"10-1002",
             "qty":1,
             "quote_id":"2"
          }
       ],
       "otherInfo":"sampleInfo"
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2015-07-21
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多