Home > Enterprise >  How to generate Request Body like this [{"key":"available","value":&qu
How to generate Request Body like this [{"key":"available","value":&qu

Time:01-23

My server is accepting request body like this:

[
 {
  "key":"available",
  "value":"1"
 }
]

I have a interface like this:

@POST("lm/leave")
suspend fun requestLeave(
    @Body body: RequestBody
): Response<LeaveResponse>

What I have tried:

val lReq: HashMap<String, String> = HashMap()
    lReq.put("available", "1")

How and what should I use to generate a request like above ? Any help will be appreciated!

CodePudding user response:

You can use JSONObject and JSONArray to create the request you need:

val jsonObj = JSONObject()
jsonObj.put("available", "1")

val jsonArray = JSONArray()
jsonArray.put(jsonObj)

val requestBody = RequestBody.create(null, jsonArray.toString())
requestLeave(requestBody)

JSONObject is responsible for the creating of object data representation in a json format:

 {
  "key":"available",
  "value":"1"
 }

JSONArray wraps the object into an array representation:

[
    {
     "key":"available",
     "value":"1"
    }
]
  •  Tags:  
  • Related