Kotlin – Convert object to/from JSON string using Gson

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

Related Posts:
How to work with Kotlin HashMap
Kotlin List & Mutable List tutorial with examples

Kotlin – Convert Object to JSON and vice versa using Jackson
Kotlin – Convert object of a Data Class to another Data Class object
Kotlin Android – Read JSON file from assets using Gson

Support Tool: Json Formatter

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<String>
) {
	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

Gson.toJson() method

com.google.gson.Gson also provides toJson() method for JSON serialization.

public String toJson(src, typeOfSrc)
  • src: type of the desired object
  • typeOfSrc: could be a Data Class type, List type, Array type, Map type…

Kotlin parse JSON to Data Class Object

The example shows you how to:

  • convert 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<String>) {
	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<String>) {
	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<Map<String, Any>>() {}.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<Map<String, Any>>() {}.type

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

And the result after running the code will be:

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

We can also apply these methods to parse JSON file from assets in an Android Application.

Convert Object to JSON string in Kotlin

The examples will show you how to convert Data Class/List/Array/Map object to JSON string.

If you want to get pretty JSON, you can use an additional package called com.google.gson.GsonBuilder with setPrettyPrinting() and create() method.

Data Class object to JSON string

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.GsonBuilder

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

fun main(args: Array<String>) {
	val gson = Gson()
	val gsonPretty = GsonBuilder().setPrettyPrinting().create()

	val tut = Tutorial("Tut #1", "bezkoder", listOf("cat1", "cat2"))

	val jsonTut: String = gson.toJson(tut)
	println(jsonTut)

	val jsonTutPretty: String = gsonPretty.toJson(tut)
	println(jsonTutPretty)
}

Check result:

{"title":"Tut #1","author":"bezkoder","categories":["cat1","cat2"]}
{
  "title": "Tut #1",
  "author": "bezkoder",
  "categories": [
    "cat1",
    "cat2"
  ]
}

List to JSON string

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.GsonBuilder

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

fun main(args: Array<String>) {
	val gson = Gson()
	val gsonPretty = GsonBuilder().setPrettyPrinting().create()

	val tutsList: List<Tutorial> = listOf(
		Tutorial("Tut #1", "bezkoder", listOf("cat1", "cat2")),
		Tutorial("Tut #2", "zkoder", listOf("cat3", "cat4"))
	);

	val jsonTutsList: String = gson.toJson(tutsList)
	println(jsonTutsList)
	
	val jsonTutsListPretty: String = gsonPretty.toJson(tutsList)
	println(jsonTutsListPretty)
}

Check result:

[{"title":"Tut #1","author":"bezkoder","categories":["cat1","cat2"]},{"title":"Tut #2","author":"zkoder","categories":["cat3","cat4"]}]
[
  {
    "title": "Tut #1",
    "author": "bezkoder",
    "categories": [
      "cat1",
      "cat2"
    ]
  },
  {
    "title": "Tut #2",
    "author": "zkoder",
    "categories": [
      "cat3",
      "cat4"
    ]
  }
]

Array to JSON string

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.GsonBuilder

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

fun main(args: Array<String>) {
	val gson = Gson()
	val gsonPretty = GsonBuilder().setPrettyPrinting().create()

	val tutsArray: Array<Tutorial> = arrayOf(
		Tutorial("Tut #3", "bezkoder", listOf("catA", "catB")),
		Tutorial("Tut #4", "zkoder", listOf("catC", "catD"))
	);

	val jsonTutsArray: String = gson.toJson(tutsArray)
	println(jsonTutsArray)
	
	val jsonTutsArrayPretty: String = gsonPretty.toJson(tutsArray)
	println(jsonTutsArrayPretty)
}

Check result:

[{"title":"Tut #3","author":"bezkoder","categories":["catA","catB"]},{"title":"Tut #4","author":"zkoder","categories":["catC","catD"]}]
[
  {
    "title": "Tut #3",
    "author": "bezkoder",
    "categories": [
      "catA",
      "catB"
    ]
  },
  {
    "title": "Tut #4",
    "author": "zkoder",
    "categories": [
      "catC",
      "catD"
    ]
  }
]

Map to JSON string

package com.bezkoder.kotlin.jsonparser

import com.google.gson.Gson
import com.google.gson.GsonBuilder

fun main(args: Array<String>) {
	val gson = Gson()
	val gsonPretty = GsonBuilder().setPrettyPrinting().create()

	val tutMap: Map<String, Any> =
		mapOf("title" to "KL Tut", "author" to "bezkoder", "categories" to listOf("catX", "catY"))

	val jsonTutMap: String = gson.toJson(tutMap)
	println(jsonTutMap)
	
	val jsonTutMapPretty: String = gsonPretty.toJson(tutMap)
	println(jsonTutMapPretty)
}

Check result:

{"title":"KL Tut","author":"bezkoder","categories":["catX","catY"]}
{
  "title": "KL Tut",
  "author": "bezkoder",
  "categories": [
    "catX",
    "catY"
  ]
}

Conclusion

Today we’re known how to parse JSON to Data Class, Array/List, Map in Kotlin, we also convert object to JSON String.

The steps can be summarized as:

  • Add Gson library
  • Define desired Class or Type (using TypeToken)
  • Use Gson.fromJson() or Gson.toJson() with Class or Type above
  • Use additional package GsonBuilder to get pretty JSON

You can also apply these methods to read and parse JSON file from assets in an Android Application.

Happy learning! See you again.

Further Reading

8 thoughts to “Kotlin – Convert object to/from JSON string using Gson”

  1. Syntax error?

    val mapType = object : TypeToken>() {}.type
    var tutorialMap: Map = gson.fromJson(json, object : TypeToken>() {}.type)
    
    1. Hi, thank you for pointing out the error.
      This is just a typo when using code syntax highlight plugin. I fixed it, now you can check it again.

      Regards,
      bezkoder

Comments are closed to reduce spam. If you have any question, please send me an email.