如何在kotlin中生成json对象? [英] how to generate a json object in kotlin?
问题描述
我真的是编程新手,最近在Kotlin用Android Studio启动了一个项目.
I'm really new in programming, and recently started a project in Kotlin with Android Studio.
因此,我对JSON对象有疑问.我从BroadcastReceiver对象(更具体地说是String)获取数据,格式如下:
So, I have a problem with a JSON object. I get data from an BroadcastReceiver object, a String to be more specific, with the next format:
{"s1":1}
这是一个简单的字符串.因此,我对Json进行了函数调用,然后执行了此操作.
This, is a simple string. So I took in a function call toJson and I do this.
private fun toJson(data:String): JSONObject {
var newData: String = data.replace("\"","")
newData = newData.replace("{","")
newData = newData.replace("}","")
val newObject = newData.split(":")
val name = newObject[0]
val value = newObject[1]
val rootObject = JSONObject()
rootObject.put(name,value)
return rootObject
}
我做对了吗?如何改善代码?
Im doing this the right way?, how can I improve my code?
感谢您的帮助,对不起我的英语!
Thanks for your help, and sorry for my english!
推荐答案
欢迎使用StackOverflow!
Welcome to StackOverflow!
在2019年,没有人真正手动解析JSON.使用 Gson 库要容易得多.它以您的对象作为输入,并吐出JSON字符串,反之亦然.
In 2019 no-one is really parsing JSON manually. It's much easier to use Gson library. It takes as an input your object and spits out JSON string and vice-versa.
示例:
data class MyClass(@SerializedName("s1") val s1: Int)
val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)
这样,您不必直接使用JSON字符串,而可以使用类型安全且更加方便的Kotlin对象.看一下文档.它很大而且易于理解
This way you're not working with JSON string directly but rather with Kotlin object which is type-safe and more convenient. Look at the docs. It's pretty big and easy to understand
以下是一些教程:
- https://www.youtube.com/watch?v=f-kcvxYZrB4
- http://www.studytrails.com/java/json/java-google-json-introduction/
- https://www.tutorialspoint.com/gson/index.htm
更新:如果您确实要使用JSONObject,则将其构造函数与一个字符串参数一起使用,该参数将自动解析您的JSON字符串.
UPDATE: If you really want to use JSONObject then use its constructor with a string parameter which parses your JSON string automatically.
val jsonObject = JSONObject(data)
这篇关于如何在kotlin中生成json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!