Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a json object in kotlin?

Tags:

android

kotlin

I'm really new in programming, and recently started a project in Kotlin with Android Studio.

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}

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!

like image 575
Luippo Avatar asked Sep 25 '19 14:09

Luippo


1 Answers

Welcome to StackOverflow!

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.

Example:

data class MyClass(@SerializedName("s1") val s1: Int)

val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)

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

Here is some tutorials:

  • 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

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)
like image 79
GV_FiQst Avatar answered Oct 13 '22 03:10

GV_FiQst