kotlin-parse-json-object-array-map-feature-image

How to parse JSON in Kotlin using Gson

In this tutorial, we’re gonna look at way to parse JSON into Data Class, Array and Map in Kotlin with the help of Gson library.


Add Gson to your Kotlin project

Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object.

We have some ways to add Gson library to our Kotlin project.

  • Gradle/Android:
  • dependencies {
      implementation 'com.google.code.gson:gson:2.8.5'
    }
    
  • Maven:
  • <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
    </dependency>
    
  • Jar:
  • Go to Maven Repository and download .jar file.

Create a Kotlin Data Class

We will need a plain Class first. Let’s call it Tutorial.

models/Tutorial.kt

package com.bezkoder.kotlin.jsonparser.models

class Tutorial(
	val title: String,
	val author: String,
	val categories: List
) {
	override fun toString(): String {
		return "Category [title: ${this.title}, author: ${this.author}, categories: ${this.categories}]"
	}
}

Gson.fromJson() method

com.google.gson.Gson package provides helpful method for deserializing JSON called fromJson().

public <T> T fromJson​(json, classOfT) throws JsonSyntaxException
public <T> T fromJson​(json, typeOfT) throws JsonSyntaxException
  • T: type of the desired object
  • json: could be a JsonElement object, a Reader object or a String
  • classOfT: class of T
  • typeOfT: specific genericized type

Kotlin parse JSON to Data Class Object

The example shows you how to:

  • parse JSON to Data Class from a String object
  • parse JSON to Data Class from a JSON file with FileReader

app.kt

package com.bezkoder.kotlin.jsonparser

import java.io.FileReader
import com.google.gson.Gson

import com.bezkoder.kotlin.jsonparser.models.Tutorial

fun main(args: Array) {
	val json = """{"title": "Kotlin Tutorial #1", "author": "bezkoder", "categories" : ["Kotlin","Basic"]}"""
	val gson = Gson()

	val tutorial_1: Tutorial = gson.fromJson(json, Tutorial::class.java)
	println("> From JSON String:\n" + tutorial_1)

	val tutorial_2: Tutorial = gson.fromJson(FileReader("tutorial.json"), Tutorial::class.java)
	/* tutorial.json
	{
		"title": "Kotlin Tutorial #2",
		"author": "bezkoder",
		"categories": [
			"Kotlin",
			"Basic"
		],
		"dummy": "dummy text"
	}
	*/
	println("> From JSON File:\n" + tutorial_2)
}

The result in console looks like this-

> From JSON String:
Category [title: Kotlin Tutorial #1, author: bezkoder, categories: [Kotlin, Basic]]
> From JSON File:
Category [title: Kotlin Tutorial #2, author: bezkoder, categories: [Kotlin, Basic]]

Kotlin parse JSON to Array or List

Because the object we want to parse JSON to is an array-like object. So we must use fromJson​(json, typeOfT).

By default, Kotlin/Java doesn’t provide a way to represent generic types.
To get Type of an Array, we use TypeToken.

For example, to create a type literal for Array, we create an empty anonymous inner class like this:

val arrayTutorialType = object : TypeToken<Array<Tutorial>>() {}.type

Let’s do the parsing right now.

app.kt

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

import com.bezkoder.kotlin.jsonparser.models.Tutorial

fun main(args: Array) {
	val jsonList =
		"""[{"title":"Kotlin Tutorial #1","author":"bezkoder","categories":["Kotlin, Basic"]},
			{"title":"Kotlin Tutorial #2","author":"bezkoder","categories":["Kotlin, Practice"]}]"""

	val gson = Gson()
	val arrayTutorialType = object : TypeToken<Array<Tutorial>>() {}.type

	var tutorials: Array<Tutorial> = gson.fromJson(jsonList, arrayTutorialType)
	tutorials.forEachIndexed  { idx, tut -> println("> Item ${idx}:\n${tut}") }
}

Now check the result:

> Item 0:
Category [title: Kotlin Tutorial #1, author: bezkoder, categories: [Kotlin, Basic]]
> Item 1:
Category [title: Kotlin Tutorial #2, author: bezkoder, categories: [Kotlin, Practice]]

The way we use Gson to parse JSON to List, MutableList or ArrayList are the same.

We only need to change the input type:

// List
val listTutorialType = object : TypeToken<List<Tutorial>>() {}.type
var tutorials: List<Tutorial> = gson.fromJson(jsonList, listTutorialType)

// MutableList
val mutableListTutorialType = object : TypeToken<MutableList<Tutorial>>() {}.type
var tutorials: MutableList<Tutorial> = gson.fromJson(jsonList, mutableListTutorialType)

// ArrayList
val arrayListTutorialType = object : TypeToken<ArrayList<Tutorial>>() {}.type
var tutorials: ArrayList<Tutorial> = gson.fromJson(jsonList, arrayListTutorialType)

The major difference among these Type is that:
Array has a fixed size, but it is mutable.
List can adjust its size dynamically, but unmutable.
MutableList is mutable and we can adjust its size dynamically.
ArrayList is a class that implements MutableList.

Kotlin parse JSON to Map

For Kotlin Map, we also need to use fromJson​(json, typeOfT) with the help of TypeToken.

val mapType = object : TypeToken>() {}.type

Let’s parse JSON to a Kotlin Map now.

app.kt

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

import com.bezkoder.kotlin.jsonparser.models.Tutorial

fun main(args: Array) {
	val json = """{"title": "Kotlin Tutorial", "author": "bezkoder", "categories" : ["Kotlin","Basic"]}"""

	val gson = Gson()
	val mapType = object : TypeToken>() {}.type

	var tutorialMap: Map = gson.fromJson(json, object : TypeToken>() {}.type)
	tutorialMap.forEach { println(it) }
}

And the result after running the code will be:

title=Kotlin Tutorial
author=bezkoder
categories=[Kotlin, Basic]

Conclusion

Today we’re known how to parse JSON to Data Class, Array/List, Map in Kotlin.
The steps can be summarized as:

  • Add Gson library
  • Define desired Class or Type (using TypeToken)
  • Use Gson.fromJson() with Class or Type above

Happy learning! See you again.

Further Reading

Leave a Reply

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