gson 如何在Kotlin中将Map转换为Json字符串?

w8rqjzmb  于 2022-12-04  发布在  Kotlin
关注(0)|答案(1)|浏览(331)

我有一个可变Map,

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

我想把它转换成json字符串
输出应该是,

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

目前,我使用的是Gson库,

val json = gson.toJson(invoiceAdditionalAttribute)

并且输出被

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

i7uaboj41#

右边的json formatting string为:

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

所以这是正确的方法得到它:

val json = gson.toJson(invoiceAdditionalAttribute)

如果要将字符串格式化为以下格式:

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

只需将:替换为=

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

但是如果你真的想让一个字符串中有反斜杠,并且clinetId值在引号内:

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

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

编辑:
正如注解中指出的,如果某些字符串值包含“:“字符,.replace(":", "=")可能是脆弱的。为了避免这种情况,我将在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()

相关问题