25

I 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
}

Am I doing this the right way? How can I improve my code?

3
  • 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) Commented Sep 25, 2019 at 14:41
  • You should check this thread. stackoverflow.com/questions/51777441/… Commented Sep 25, 2019 at 14:48
  • If one of the answers was helpful for you then I suggest you to mark it as accepted below the voting. Commented Sep 25, 2019 at 15:48

3 Answers 3

31

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)
Sign up to request clarification or add additional context in comments.

5 Comments

in all honesty gson should be part of android by now
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 {} )
For me it compiles and then fails on execution with java.lang.ClassNotFoundException: org.gradle.internal.impldep.com.google.gson.Gson
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.
11

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/

Comments

6

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.