There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released

https://github.com/Kotlin/kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.Json

@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {

    // serializing objects
    val jsonData = Json.encodeToString(MyModel.serializer(), MyModel(42))
    println(jsonData) // {"a": 42, "b": "42"}
    
    // serializing lists
    val jsonList = Json.encodeToString(MyModel.serializer().list, listOf(MyModel(42)))
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = Json.decodeFromString(MyModel.serializer(), """{"a":42}""")
    println(obj) // MyModel(a=42, b="42")
}
Answer from Elisha Sterngold on Stack Overflow
🌐
Android Developers
developer.android.com › api reference › jsonobject
JSONObject | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
People also ask

How to get value from JSON in Kotlin?
To extract values from JSON data in Kotlin, developers can parse the JSON string or object and access specific fields or properties using key-value lookups. By parsing the JSON structure and retrieving values based on keys, developers can access and manipulate data stored in JSON format efficiently.
🌐
dhiwise.com
dhiwise.com › post › kotlin-object-to-json-transformation-efficient-data-conversion
Mastering Kotlin Object to JSON Conversion
How to create a JSON object from a string in Kotlin?
In Kotlin, you can create a JSON object from a string by using JSON parsing libraries like kotlinx.serialization or GSON to deserialize the string into a JSON object for further manipulation.
🌐
dhiwise.com
dhiwise.com › post › how-to-streamline-data-processing-with-kotlin-json
Mastering Kotlin JSON Serialization for Efficient Data ...
How to pass JSON in Kotlin?
Passing JSON data in Kotlin involves creating JSON strings or objects that encapsulate the data to be transmitted or processed. Developers can pass JSON data between functions, classes, or API endpoints by serializing the data into JSON format using serialization libraries and transmitting it as needed.
🌐
dhiwise.com
dhiwise.com › post › kotlin-object-to-json-transformation-efficient-data-conversion
Mastering Kotlin Object to JSON Conversion
🌐
Kotlin
kotlinlang.org › docs › serialization.html
Serialization | Kotlin Documentation
1 month ago - Kotlin serialization supports a variety of built-in types, including all primitive types and most composite types from the Kotlin standard library like the List type. For more information, see Serialize built-in types. Additionally, classes annotated with @Serializable are fully supported for serialization, enabling the conversion of class instances to and from formats like JSON.
🌐
Kotlin
kotlinlang.org › api › kotlinx.serialization › kotlinx-serialization-json › kotlinx.serialization.json › -json-object
JsonObject | kotlinx.serialization – Kotlin Programming Language
Class representing JSON object, consisting of name-value pairs, where value is arbitrary JsonElement · Since this class also implements Map interface, you can use traditional methods like Map.get or Map.getValue to obtain Json elements.
🌐
DhiWise
dhiwise.com › post › kotlin-object-to-json-transformation-efficient-data-conversion
Mastering Kotlin Object to JSON Conversion
September 5, 2024 - The language's interoperability with Java also extends its reach in handling JSON operations across various platforms and environments. In Kotlin, data classes play a pivotal role in representing structured data objects that can be easily converted to JSON format.
🌐
DhiWise
dhiwise.com › post › how-to-streamline-data-processing-with-kotlin-json
Mastering Kotlin JSON Serialization for Efficient Data ...
July 10, 2024 - In the modern software development, [Kotlin JSON] stands as a pivotal tool for seamless data interchange. Using the kotlinx.serialization library, developers can effortlessly convert Kotlin objects to JSON and vice versa, ushering in a new era of data transformation efficiency.
🌐
BezKoder
bezkoder.com › home › kotlin – convert json to object and vice versa using jackson
Kotlin – Convert JSON to Object and vice versa using Jackson - BezKoder
December 13, 2020 - Jackson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object.
Find elsewhere
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-in-kotlin-with-jackson
Reading and Writing JSON in Kotlin with Jackson
February 27, 2023 - Oftentimes, we're dealing with lists and arrays, rather than singular objects. Let's take a look at how we can serialize a Kotlin List into a JSON array. Using the same data class, we'll create a list of Users and serialize them into a JSON array: ... Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet.
🌐
Medium
medium.com › @midoripig1009 › working-with-json-in-kotlin-parsing-and-serialization-a62300ec43b8
Working with JSON in Kotlin: Parsing and Serialization | by CuriousCat | Medium
October 28, 2023 - We then use the encodeToString function from the Json object to serialize the User object into a JSON string. In this blog post, we have learned how to parse and serialize JSON in Kotlin using the kotlinx.serialization library.
🌐
BezKoder
bezkoder.com › home › kotlin – convert object to/from json string using gson
Kotlin - Convert object to/from JSON string using Gson - BezKoder
April 11, 2020 - Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object.
🌐
ZetCode
zetcode.com › kotlin › json
Kotlin JSON - JSON serialization and deserialization in Kotlin
January 29, 2024 - In the example, we write an object into JSON. We use GsonBuilder to create Gson.
Top answer
1 of 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:

  • 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)
2 of 3
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/

🌐
Kotlin
kotlinlang.org › api › kotlinx.serialization › kotlinx-serialization-json › kotlinx.serialization.json › -json
Json | kotlinx.serialization – Kotlin Programming Language
Json instance can be configured in its Json {} factory function using JsonBuilder. For demonstration purposes or trivial usages, Json companion can be used instead. Then constructed instance can be used either as regular SerialFormat or StringFormat ...
🌐
DhiWise
dhiwise.com › post › simplifying-kotlin-string-to-json-conversion
The Ultimate Guide to Kotlin String to JSON Conversion
June 14, 2024 - It serves as a textual representation ... Kotlin string to a JSON object involves transforming the string representation of JSON data into a usable JSON object for programmatic manipulation....
🌐
Kotlin
kotlinlang.org › api › kotlinx.serialization › kotlinx-serialization-json › kotlinx.serialization.json › build-json-object.html
buildJsonObject | kotlinx.serialization – Kotlin Programming Language
kotlinx-serialization-json/kotlinx.serialization.json/buildJsonObject · inline fun buildJsonObject(builderAction: JsonObjectBuilder.() -> Unit): JsonObject(source) Builds JsonObject with the given builderAction builder. Example of usage: val json = buildJsonObject { put("booleanKey", true) putJsonArray("arrayKey") { for (i in 1..10) add(i) } putJsonObject("objectKey") { put("stringKey", "stringValue") } } Content copied to clipboard ·
🌐
Stack Overflow
stackoverflow.com › questions › 75448485 › how-to-convert-json-object-with-objects-to-json-array-with-objects
kotlin - How to convert json object with objects to json array with objects - Stack Overflow
To convert the given JSON object to a list of Notification objects, you can iterate over the key-value pairs in the "Items" object and create a Notification object for each non-null value. Here's some sample Kotlin code that demonstrates this:
🌐
Scaler
scaler.com › home › topics › converting kotlin data class from json using gson
Converting Kotlin Data Class from JSON using GSON - Scaler Topics
November 6, 2023 - Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object.
🌐
Kotlin
kotlinlang.org › docs › serialization-configure-json-serialization.html
JSON serialization overview | Kotlin Documentation
1 month ago - Kotlin serialization allows you to easily convert Kotlin objects to JSON and back. The Json class is the primary tool for this, offering flexibility in how JSON is generated and parsed.