JSON Parser in Kotlin : 3 Easy Steps to Get Data from JSON
Creating a JSON parser in Kotlin is a relatively easy task with IntelliJ IDEA because we need a dependency to handle JSON data. If you are familiar with Android Studio, you can use it too. However, here we focus on illustrating how to create a new Kotlin parser using IntelliJ IDEA. This tutorial is also beneficial for Android developers because it shows how to read JSON data and display it in our console.
In this example, we’ll use a collection of books in your home library as an illustration. The book information is stored as JSON. We need to extract the data and print it on the console.
Step 1: Add a dependency
To handle JSON data, we need to include a dependency in our IDE. Add the following JSON dependency as a module in JetBrains IntelliJ IDEA.
Read more about adding dependencies in IntelliJ IDEA
org.json:json:20231013
File > Project Structure > Modules > Dependencies
JSON (Books)
{
"title": "Books",
"description": "Collection of books in your library",
"items": [
{
"id": 1,
"title": "Atomic Habits",
"image": "image1.png",
"content": "The book explores the idea that small, incremental changes, or atomic habits, can lead to remarkable results over time. ",
"tags": ["psychology", "behavioral science"]
},
{
"id": 2,
"title": "Wonder",
"image": "image2.png",
"content": "The book, published in 2012, tells the inspiring and heartwarming story of August Pullman, a fifth-grade boy with facial differences.",
"tags": ["personal growth", "empathy"]
},
{
"id": 3,
"title": "Deep Work",
"image": "image3.png",
"content": "The book explores the concept of deep work",
"tags": ["non-fiction", "self-help"]
}
]
}
Step 2 : Create a Data Class
In Kotlin, the data class is a special type of class primarily used to hold data. Let’s create a data class.
data class Books(
val id: Int,
val title: String,
val image: String,
val content: String,
val tags: List<String>
)
Step 3: Create a JSON parser Class in Kotlin
class JsonParser(jsonString: String) {
private val jsonObject: JSONObject = JSONObject(jsonString)
private fun parseItems(): List<Books> {
val itemsArray: JSONArray = jsonObject.getJSONArray("items")
val itemsList = mutableListOf<Books>()
for (i in 0 until itemsArray.length()) {
val itemObject = itemsArray.getJSONObject(i)
val id = itemObject.getInt("id")
val title = itemObject.getString("title")
val image = itemObject.getString("image")
val content = itemObject.getString("content")
val tags = itemObject.getJSONArray("tags").toList().map { it.toString() }
val item = Books(id, title, image, content, tags)
itemsList.add(item)
}
return itemsList
}
fun displayItems() {
val items = parseItems()
for (item in items) {
println("ID: ${item.id}")
println("Title: ${item.title}")
println("Image: ${item.image}")
println("Content: ${item.content}")
println("Tags: ${item.tags.joinToString(", ")}")
println()
}
}
}
Let’s use in the main() function:
val jsonParser = JsonParser(json)
jsonParser.displayItems()
extract_json.kt (Complete):
import org.json.JSONArray
import org.json.JSONObject
data class Books(
val id: Int,
val title: String,
val image: String,
val content: String,
val tags: List<String>
)
class JsonParser(jsonString: String) {
private val jsonObject: JSONObject = JSONObject(jsonString)
private fun parseItems(): List<Books> {
val itemsArray: JSONArray = jsonObject.getJSONArray("items")
val itemsList = mutableListOf<Books>()
for (i in 0 until itemsArray.length()) {
val itemObject = itemsArray.getJSONObject(i)
val id = itemObject.getInt("id")
val title = itemObject.getString("title")
val image = itemObject.getString("image")
val content = itemObject.getString("content")
val tags = itemObject.getJSONArray("tags").toList().map { it.toString() }
val item = Books(id, title, image, content, tags)
itemsList.add(item)
}
return itemsList
}
fun displayItems() {
val items = parseItems()
for (item in items) {
println("ID: ${item.id}")
println("Title: ${item.title}")
println("Image: ${item.image}")
println("Content: ${item.content}")
println("Tags: ${item.tags.joinToString(", ")}")
println()
}
}
}
fun main() {
val json = """
{
"title": "Books",
"description": "Collection of books in your library",
"items": [
{
"id": 1,
"title": "Atomic Habits",
"image": "image1.png",
"content": "The book explores the idea that small, incremental changes, or atomic habits, can lead to remarkable results over time. ",
"tags": ["psychology", "behavioral science"]
},
{
"id": 2,
"title": "Wonder",
"image": "image2.png",
"content": "The book, published in 2012, tells the inspiring and heartwarming story of August Pullman, a fifth-grade boy with facial differences.",
"tags": ["personal growth", "empathy"]
},
{
"id": 3,
"title": "Deep Work",
"image": "image3.png",
"content": "The book explores the concept of deep work",
"tags": ["non-fiction", "self-help"]
}
]
}
""".trimIndent()
val jsonParser = JsonParser(json)
jsonParser.displayItems()
}
Output :
ID: 1
Title: Atomic Habits
Image: image1.png
Content: The book explores the idea that small, incremental changes, or atomic habits, can lead to remarkable results over time.
Tags: psychology, behavioral science
ID: 2
Title: Wonder
Image: image2.png
Content: The book, published in 2012, tells the inspiring and heartwarming story of August Pullman, a fifth-grade boy with facial differences.
Tags: personal growth, empathy
ID: 3
Title: Deep Work
Image: image3.png
Content: The book explores the concept of deep work
Tags: non-fiction, self-help
Overview for Future Learning:
JSON is a lightweight data interchange format that is easy for humans to read and write, and it’s widely used for data exchange between a server and a client or between different components of an application.
Create Kotlin data classes that represent the structure of your data. These classes will be used to map the JSON data to Kotlin objects during deserialization.
Encoding vs Decoding :
Encoding(Serialization) : Convert Kotlin objects into JSON format. This is useful when you need to send data from your application to an external service or save it in a file.
Decoding(Deserialization) : Convert JSON data into Kotlin objects. This is useful when you receive JSON data from an external source, such as an API.
Happy Coding!