如何在Kotlin中将地图转换为Json字符串? [英] How to convert a map to Json string in kotlin?

查看:390
本文介绍了如何在Kotlin中将地图转换为Json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mutableMap,

I have a mutableMap,

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

我想将其转换为json字符串

I want to convert it into json string

输出应为

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

当前,我正在使用Gson库,

Currently, I am using Gson library,

val json = gson.toJson(invoiceAdditionalAttribute)

输出为

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

推荐答案

正确的 json格式设置字符串是:

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

所以这是正确的方法:

val json = gson.toJson(invoiceAdditionalAttribute)

如果您想要这样的字符串格式:

If you want a string formatted like this:

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

只需将:替换为=:

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

但是,如果您真的想在反引号中包含一个带有反斜杠和clinetId值的字符串:

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("\"", "\\\"")

如所指出的,如果某些字符串值包含:",则注释.replace(":", "=")可能是脆弱的.特点. 为了避免这种情况,我会在Map<String, Any?>上写一个自定义扩展功能:

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

这篇关于如何在Kotlin中将地图转换为Json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆