如何在 Kotlin 中从字符串创建 JSONObject?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44295665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:53:57  来源:igfitidea点击:

How to create a JSONObject from String in Kotlin?

jsonkotlin

提问by nkukday

I need to convert a string {\"name\":\"test name\", \"age\":25}to a JSONObject

我需要将字符串转换{\"name\":\"test name\", \"age\":25}为 JSONObject

回答by Ryba

Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why

也许我误解了这个问题,但听起来你已经在使用 org.json 这引出了一个关于为什么的问题

val answer = JSONObject("""{"name":"test name", "age":25}""")

wouldn't be the best way to do it? What was wrong with the built in functionality of JSONObject?

不会是最好的方法吗?JSONObject 的内置功能有什么问题?

回答by arjun shrestha

val rootObject= JSONObject()
rootObject.put("name","test name")
rootObject.put("age","25")

回答by Akshar Patel

You can use https://github.com/cbeust/klaxonlibrary.

您可以使用https://github.com/cbeust/klaxon库。

val parser: Parser = Parser()
val stringBuilder: StringBuilder = StringBuilder("{\"name\":\"Cedric Beust\", \"age\":23}")
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
println("Name : ${json.string("name")}, Age : ${json.int("age")}")

Result :

结果 :

Name : Cedric Beust, Age : 23

回答by Maneki Neko

The approaches above are a bit dangerous: They don't provide a solution for illegal chars. They don't do the escaping... And we hate to do the escaping ourselves, don't we?

上面的方法有点危险:它们没有为非法字符提供解决方案。他们不做逃避......我们讨厌自己逃避,不是吗?

So here's what I did. Not that cute and clean but you have to do it only once.

所以这就是我所做的。不是那么可爱和干净,但你只需要做一次。

class JsonBuilder() {
    private var json = JSONObject()

    constructor(vararg pairs: Pair<String, *>) : this() {
        add(*pairs)
    }

    fun add(vararg pairs: Pair<String, *>) {
        for ((key, value) in pairs) {
            when (value) {
                is Boolean -> json.put(key, value)
                is Number -> add(key, value)
                is String -> json.put(key, value)
                is JsonBuilder -> json.put(key, value.json)
                is Array<*> -> add(key, value)
                is JSONObject -> json.put(key, value)
                is JSONArray -> json.put(key, value)
                else -> json.put(key, null) // Or whatever, on illegal input
            }
        }
    }

    fun add(key: String, value: Number): JsonBuilder {
        when (value) {
            is Int -> json.put(key, value)
            is Long -> json.put(key, value)
            is Float -> json.put(key, value)
            is Double -> json.put(key, value)
            else -> {} // Do what you do on error
        }

        return this
    }

    fun <T> add(key: String, items: Array<T>): JsonBuilder {
        val jsonArray = JSONArray()
        items.forEach {
            when (it) {
                is String,is Long,is Int, is Boolean -> jsonArray.put(it)
                is JsonBuilder -> jsonArray.put(it.json)
                else -> try {jsonArray.put(it)} catch (ignored:Exception) {/*handle the error*/}
            }
        }

        json.put(key, jsonArray)

        return this
    }

    override fun toString() = json.toString()
}

Sorry, might have had to cut off types that were unique to my code so I might have broken some stuff - but the idea should be clear

抱歉,可能不得不切断我的代码独有的类型,所以我可能破坏了一些东西 - 但这个想法应该很清楚

You might be aware that in Kotlin, "to" is an infix method that converts two objects to a Pair. So you use it simply like this:

您可能知道在 Kotlin 中,“to”是一种将两个对象转换为 Pair 的中缀方法。所以你可以像这样简单地使用它:

   JsonBuilder(
      "name" to "Amy Winehouse",
      "age" to 27
   ).toString()

But you can do cuter things:

但是你可以做更可爱的事情:

JsonBuilder(
    "name" to "Elvis Presley",
    "furtherDetails" to JsonBuilder(
            "GreatestHits" to arrayOf("Surrender", "Jailhouse rock"),
            "Genre" to "Rock",
            "Died" to 1977)
).toString()