Skip to content

How to parse JSON in Kotlin? Asif Spark By {Examples}

  • by

How to parse JSON String in Kotlin? JSON(JavaScript Object Notation) is a very popular data interchange format. This is used extensively in web applications for data transfer between the APIs. Other programming languages also support the JSON format, you first need to parse it to extract meaningful information from the data format. 

Parsing JSON is a process to extract meaningful data from any JSON. Often we parse JSON String into JSON Objects. In this article, we will learn how to parse JSON in Kotlin.

Using the JSONObject Class To Parse JSON String in Kotlin

The JSONObject class in Kotlin provides a convenient way to parse the JSON objects. This class is a part of the ‘org.json’ package. It is more convenient to work with the small and medium-sized JSON String. First, you must create an instance of the JSON object by passing the JSON String to the constructor. Next, you can use the available methods of the object, like getString(), getInt(), etc, to extract the values from the JSON object. 

While this approach offers convenience, it does have some limitations. For instance, being a third-party library, it may not be optimized for handling large JSON. Additionally, it lacks automatic type conversion for nested JSON structures, which can be a drawback.

Since this is a third-party library, you must add dependencies to your project. So go to the build.gradle file and add the following lines under the dependencies:

// Dependency in build.gradle
implementation(“org.json:json:20230227”)

Example code:

The below is a complete example that parses the JSON string in Kotlin.

// Import the library in the code
import org.json.JSONObject

// Create the function which can parse the
fun parseJSON(jsonString: String) {
// Create a JSONObject and pass the json string
val jsonObject = JSONObject(jsonString)

val name = jsonObject.getString(“name”)
val age = jsonObject.getInt(“age”)
val isStudent = jsonObject.getBoolean(“isStudent”)

// Use the extracted values and print them
println(“Name: $name”)
println(“Age: $age”)
println(“Is Student: $isStudent”)
}

// Driver code of the program
fun main() {
// Define the String
val jsonString = “””
{
“name”: “John Doe”,
“age”: 25,
“isStudent”: true
}
“””.trimIndent()
// Call the function
parseJSON(jsonString)
}

Output:

Explanation:

In this code, we defined two functions- parseJSON and main. The main is the driving code of our program. We first defined a JSON String named jsonString and defined the JSON object. Next, we called the parseJSON function and used the JSON String as an argument. The praseJSON function prints the values of the items of the JSON object. Under the function, we first created a JSON object using the JSONObject method of the “json” library. Finally, we used the getString, getInt, and getBoolean methods to get the values of the items by passing the corresponding keys. 

Using a Gson Library To parse JSON In Kotlin

Gson is a popular library in Koltin to deal with the JSON Object. Google originally developed the library. It provides a simple and efficient way to serialize and manipulate the JSON objects. One advantage of this library is that it automatically handles complex data types and converts them to JSON representation. The Gson library can also handle the null values within the JSON Object in Kotln, so it handles the error quite effectively. An even bigger advantage of using the Gson library is that they are very efficient in parsing JSON Objects; hence, we can use them for large JSON files. 

Before using the Gson library, we need to add the relevant dependencies to the Gradle build file. Add the following line under the dependencies.

implementation(“com.google.code.gson:gson:2.10.1”)

Example code:

// Import the libraries in the code
import com.google.gson.Gson

// Create a data class to define the class containing the variables
data class Book(val title: String, val author: String, val year: Int)

fun parseJSON(jsonString: String) {
// Define the Gson Object
val gson = Gson()
val book = gson.fromJson(jsonString, Book::class.java)

// Use the extracted values
println(“Title: ${book.title}”)
println(“Author: ${book.author}”)
println(“Year: ${book.year}”)
}

fun main() {
// Define the JSON String
val jsonString = “””
{
“title”: “The Great Gatsby”,
“author”: “F. Scott Fitzgerald”,
“year”: 1925
}
“””.trimIndent()
// Call the parseJSON function
parseJSON(jsonString)
}

Output:

Explanation:

First, we imported the Google Gson class into our code. Next, we have created the data class, which acts as the data container and contains all the data of the JSON String we will define. Note that we should define this only after we know the JSON Object beforehand. Next, we defined the parseJSON function, which takes the JSON String as the parameter and prints the associated values. In the fromJson method of the Gson object, the function parses the jsonString parameter and converts it into a Book object. Book::class.java argument specifies the target class type to which the JSON should be deserialized. Finally, we used dot notation to get and print the values of the JSON Object.

Using Kotlin Serialization To Parse JSON 

The Serialization library of Kotlin supports serializing objects in various formats, which includes JSON Objects. The library uses annotation to mark a class serializable(@serializable). It supports nested JSON Objects to be serialized and manipulated. One advantage of using this library is that it ensures type safety, and hence there are fewer chances of run-time errors. The library is optimized and efficient compared to the JSONObject library.

Since this is a third-party library, we must add dependencies and implementation. 

In the Gradle build file, add the following implementation:

implementation(“org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0”)

Next, add the following plugin:

kotlin(“plugin.serialization”) version “1.8.22”

Now sync the Gradle to download all the dependencies. 

Example code:

// Import all the packages and classes we need to run the code
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

// mark the data class Person to be serializable
@Serializable
data class Person(val name: String, val age: Int, val isStudent: Boolean)

// Define the function to extract the values of JSON Object
fun parseJSON(jsonString: String) {
val person = Json.decodeFromString(jsonString)

// Use the extracted values
println(“Name: ${person.name}”)
println(“Age: ${person.age}”)
println(“Is Student: ${person.isStudent}”)
}

// Define the main function
fun main() {
// Define a JSON Object in the form of String
val jsonString = “””
{
“name”: “Alice Smith”,
“age”: 30,
“isStudent”: false
}
“””.trimIndent()
// Call the parseJSON function
parseJSON(jsonString)
}

Output:

Explanation:

In the above code, we first imported the serialization library in the code. Next, we have defined the Person as a data class. We marked this as serializable. Next, we defined a function named parse JSON which takes the JSON from a String and parse it. Under the function, we used the decodeFromString method to decode the JSON from String into Object. The main function is our driver code, and we defined a JSON String called the parseJSON function.

Use The Jackson Library To Parse String In Kotlin

Jackson is a popular library of Kotlin to parse and manipulate JSON data. The library supports both the reading as well as writing JSON data. The advantage of using this library is that we do not need to parse the data manually. The library is optimized to handle null values, date and time formatting, and more. Since the library is well-optimized, we can use this for handling complex and large JSON Objects. 

implementation(“org.codehaus.jackson:jackson-mapper-asl:1.9.13”)

Example code:

// Import the necessary libraries and packages
import org.codehaus.jackson.map.ObjectMapper

// Define a class to store the data types of the car information
class Car {
var brand: String? = null
var model: String? = null
var year: Int? = null
var owner: Owner? = null

// Override the toString() function to provide a custom string representation of the Car object
override fun toString(): String {
return “Car(brand=$brand, model=$model, year=$year, owner=$owner)”
}
}

// Define a class to store the data types of the owner information
class Owner {
var name: String? = null
var age: Int? = null
var address: String? = null

// Override the toString() function to provide a custom string representation of the Owner object
override fun toString(): String {
return “Owner(name=$name, age=$age, address=$address)”
}
}

// Driver code of the program
fun main() {
// Define the JSON string representing the car and owner information
val jsonString = “{“brand”:”Toyota”,”model”:”Corolla”,”year”:2020,” +
“”owner”:{“name”:”John Doe”,”age”:35,” +
“”address”:”123 Main St”}}”

println(“JSON string is: $jsonString”)

// Parse the JSON string and deserialize it into a Car object
val car = ObjectMapper().readValue(jsonString, Car::class.java)
println(“Car object: $car”)
}

Output:

Explanation:

In the following code, we have used the ObjectMapper to parse the JSON Objects. We defined two classes named Car and Owner to hold the data type of the data. The main is the driver code, and we first defined a JSON String here. Next, we used the ObjectMapper method to parse the JSON String.

Conclusion

In this article, we understood how to parse JSON in Kotlin. We have multiple ways to parse the JSON Object in Kotlin. We have the JSONObject library, which offers a convenient way to parse JSON String in Kotlin. However, this is inefficient and has limitations. The Gson and the Serialization libraries provide a much better and optimized way to parse the JSON Objects in Kotlin. While the JSONObject library is well suited for small JSON Objects, the other two are better choices for large JSON Objects. 

 How to parse JSON String in Kotlin? JSON(JavaScript Object Notation) is a very popular data interchange format. This is used extensively in web applications for data transfer between the APIs. Other programming languages also support the JSON format, you first need to parse it to extract meaningful information from the data format.  Parsing JSON is  Read More Kotlin 

Leave a Reply

Your email address will not be published. Required fields are marked *