How to convert a map to Json string in kotlin?

Viewed 2003

I have a mutableMap,

    val invoiceAdditionalAttribute = mutableMapOf<String, Any?>()
    invoiceAdditionalAttribute.put("clinetId",12345)
    invoiceAdditionalAttribute.put("clientName", "digital")
    invoiceAdditionalAttribute.put("payload", "xyz")

I want to convert it into json string

the output should be,

"{\"clinetId\"=\"12345\", \"clientName\"=\"digital\", \"payload\"=\"xyz\"}"

Currently, I am using Gson library,

val json = gson.toJson(invoiceAdditionalAttribute)

and the output is

{"clinetId":12345,"clientName":"digital","payload":"xyz"}
1 Answers

The right json formatting string is:

{"clinetId":12345,"clientName":"digital","payload":"xyz"}

So this is the right method to get it:

val json = gson.toJson(invoiceAdditionalAttribute)

If you want a string formatted like this:

{"clinetId"=12345, "clientName"="digital", "payload"="xyz"}

just replace : with =:

val json = gson.toJson(invoiceAdditionalAttribute).replace(":", "=")

But if you truly want to have a string with backslashes and clinetId value to be inside quotes:

val invoiceAdditionalAttribute = mutableMapOf<String, Any?>()
invoiceAdditionalAttribute["clinetId"] = 12345.toString()
invoiceAdditionalAttribute["clientName"] = "digital"
invoiceAdditionalAttribute["payload"] = "xyz"

val json = gson.toJson(invoiceAdditionalAttribute)
        .replace(":", "=")
        .replace("\"", "\\\"")

EDIT:

As pointed int he comments .replace(":", "=") can be fragile if some string values contain a ":" character. To avoid it I would write a custom extension function on Map<String, Any?>:

fun Map<String, Any?>.toCustomJson(): String = buildString {
    append("{")
    var isFirst = true
    this@toCustomJson.forEach {
        it.value?.let { value ->
            if (!isFirst) {
                append(",")
            }
            isFirst = false
            append("\\\"${it.key}\\\"=\\\"$value\\\"")
        }
    }

    append("}")
}

// Using extension function

val customJson = invoiceAdditionalAttribute.toCustomJson()
Related