19

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!

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Luippo
  • 193
  • 1
  • 1
  • 6
  • 1
    *Im doing this the right way?* no, this is not feasible for more complex data. You can probably create a JSONObject from a string directly. Try `JSONObject(data)` – Tim Sep 25 '19 at 14:41
  • You should check this thread. https://stackoverflow.com/questions/51777441/convert-stringified-json-to-jsonarray-using-kotlin-in-android][1] – Hritik Gupta Sep 25 '19 at 14:48
  • If one of the answers was helpful for you then I suggest you to mark it as accepted below the voting. – GV_FiQst Sep 25 '19 at 15:48

3 Answers3

26

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:

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)
GV_FiQst
  • 1,487
  • 14
  • 30
  • Thanks, the tutorials and update apart was ver usefull! – Luippo Sep 25 '19 at 18:23
  • in all honesty gson should be part of android by now – a_local_nobody Sep 25 '19 at 18:54
  • Or Moshi (see https://stackoverflow.com/questions/43577623/moshi-vs-gson-in-android and https://www.reddit.com/r/androiddev/comments/684flw/why_use_moshi_over_gson/dgx3gpm/ in particular) – Alexey Romanov Sep 26 '19 at 08:08
  • 1
    its 2022 and i am still surprised we cant write JSON directly in Kotlin backed by some DSL features. (Just like we can create objects in JS by simply using `{}` ) – Talha Jan 03 '22 at 12:03
  • For me it compiles and then fails on execution with ```java.lang.ClassNotFoundException: org.gradle.internal.impldep.com.google.gson.Gson``` – reducing activity Jul 22 '22 at 20:57
  • Gson is located inside `com.google.gson` package. The package in your exception message is different so I guess you just didn't set it up correctly. Please refer to the official documentation. – GV_FiQst Jul 30 '22 at 18:55
8

Best way is using kotlinx.serialization. turn a Kotlin object into its JSON representation and back marking its class with the @Serializable annotation, and using the provided encodeToString and decodeFromString<T> extension functions on the Json object:

import kotlinx.serialization.*
import kotlinx.serialization.json.*
​
@Serializable
data class User(val name: String, val yearOfBirth: Int)
​
   // Serialization (Kotlin object to JSON string)
​
   val data = User("Louis", 1901)
   val string = Json.encodeToString(data)
   println(string) // {"name":"Louis","yearOfBirth":1901}
​
   // Deserialization (JSON string to Kotlin object)
​
   val obj = Json.decodeFromString<User>(string)
   println(obj) // User(name=Louis, yearOfBirth=1901)

Further examples: https://blog.jetbrains.com/kotlin/2020/10/kotlinx-serialization-1-0-released/

fisio
  • 494
  • 6
  • 12
4

I am adding 3 templates here for Kotlin Developers, It will solve json converting & parsing problems.

//Json Array template
{
  "json_id": "12.4",
  "json_name": "name of the array",
  "json_image": "https://image_path",
  "json_description": "Description of the Json Array"
}

Kotlin Model class

data class JsonDataParser(
  @SerializedName("json_id") val id: Long, 
  @SerializedName("json_name") val name: String, 
  @SerializedName("json_image") val image: String,
  @SerializedName("json_description") val description: String
)

Converting to Json String from the Model Class

val gson = Gson()
val json = gson.toJson(jsonDataParser)

Parsing from Json file/Strong

val json = getJson()
val topic = gson.fromJson(json, JsonDataParser::class.java)
Takermania
  • 1,345
  • 2
  • 12
  • 20