I need to convert a string {\"name\":\"test name\", \"age\":25}
to a JSONObject
我需要将字符串{\“name\”:\“test name\”、\“age\”:25}转换为JSONObject
3 个解决方案
#1
7
You can use https://github.com/cbeust/klaxon library.
您可以使用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
#2
7
val rootObject= JSONObject()
rootObject.put("name","test name")
rootObject.put("age","25")
#3
4
Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why
也许我误解了这个问题,但听起来你已经在使用org了。这就引出了为什么会这样的问题
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的内置功能有什么问题?
#1
7
You can use https://github.com/cbeust/klaxon library.
您可以使用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
#2
7
val rootObject= JSONObject()
rootObject.put("name","test name")
rootObject.put("age","25")
#3
4
Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why
也许我误解了这个问题,但听起来你已经在使用org了。这就引出了为什么会这样的问题
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的内置功能有什么问题?