how to generate a json object in kotlin?

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)

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)

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/

Tags:

Android

Kotlin