Android Kotlin Volley How to send JSON Data

Issue

I want to use Volley send JSON payload to REST API. But I get an error

“com.android.volley.ParseError: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject”

Payload from Magento https://devdocs.magento.com/guides/v2.4/rest/tutorials/inventory/create-cart-add-products.html

JSON Payload

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

Volley Code

// 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)

Solution

You should use JSONArray instead of JSONObject. Your itemsArray must be like this:

val itemsArray JSONArray()

Your request payload must look like this and can have multiple objects:

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

The reason is because the payload now contains multiple items. You can add multiple JSONObject in the JSONArray.

Another approach can be if you want to send some other information in the request payload then you might need to use in the following manner:

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

Answered By – Mohit Ajwani

Leave a Comment