How to convert a map to Json string in kotlin?

霸气de小男生 提交于 2020-06-28 03:43:14

问题


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:


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


来源:https://stackoverflow.com/questions/62534616/how-to-convert-a-map-to-json-string-in-kotlin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!