0

Please how do I convert to OkHttp RequestBody in a way that extra backslash[\] won't get added to my string value?

My Implementation


val requestBody = mapOf("regNumber" to "CES/2020/19423").toRequestBody() // my extension func.
val buffer = Buffer()
requestBody.writeTo(buffer)
Log.d("BodyString", buffer.readUtf8())

Response BodyString: {"regNumber":"CES\/2020\/19423"}

What I Want BodyString: {"regNumber":"CES/2020/19423"}

Ehma Ugbogo
  • 418
  • 5
  • 7
  • 3
    Why do you need / want to do that? Escaping forward slashes in JSON is somewhat common, see https://stackoverflow.com/q/1580647/610979 – Frank Schmitt Jun 09 '23 at 11:20
  • Thanks @FrankSchmitt. The issue is within my toRequestBody() ext function. I just discovered that it's really a JSON issue. – Ehma Ugbogo Jun 09 '23 at 11:50

1 Answers1

0

Within my toRequestBody extension function, I previously converted my map to a JsonObject. I realized that it was the JsonObject that was including the extra backslach "\"

My final solution that resolved it

internal inline fun <reified T> T.toRequestBody(): RequestBody {
    val jsonBodyStr = Gson().toJson(this, T::class.java)
    return jsonBodyStr.toRequestBody("application/json;charset=utf8".toMediaTypeOrNull())
}
Ehma Ugbogo
  • 418
  • 5
  • 7