Kotlin – How to convert Object to/from JSON by Gson with Kotlin language

This tutorial shows you how to use Gson to convert Kotlin object to/from JSON.

I. Technology

– Java 1.8
– Kotlin 1.1.2
– Maven 3.5.1

II. Overview

1. Goal

– Convert JSON string/JSON file to Person(name:String,age:Int,messages:List) Kotlin Object/List/Map
– Convert Person Object/List/Map to JSON string.

2. Steps to do

– add Dependency:

<dependency>
	<groupId>org.jetbrains.kotlin</groupId>
	<artifactId>kotlin-stdlib</artifactId>
	<version>1.1.2</version>
</dependency>

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.0</version>
</dependency>

– import:


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

– use Gson instance:


val gson =
-> Gson()
-> GsonBuilder().setPrettyPrinting().create() // for pretty print feature

// Json String/File to Object
var person: Person = 
-> gson.fromJson(json, Person::class.java)
-> gson.fromJson(FileReader, Person::class.java)

// Json String to List/Map
-> personList: List = gson.fromJson(jsonList, object : TypeToken>() {}.type)
-> personMap: Map = gson.fromJson(json, object : TypeToken>() {}.type)

// Object/List/Map to Json String
var jsonStr : String =
-> gson.toJson(person)
-> gson.toJson(personList)
-> gson.toJson(personMap)

III. Practice

0. Person Class


package com.javasampleapproach.jsonstring

data class Person(val name: String, val age: Int, val messages: List) {
}

1. Object

1.1 from JSON


package com.javasampleapproach.jsonstring

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

fun main(args: Array) {

	val json = """{"name": "Kolineer", "age": "26", "messages" : ["Master Kotlin","At JavaSampleApproach"]}"""
	val gson = Gson()

	val person1 : Person = gson.fromJson(json, Person::class.java)
	println(person1)

	val person2: Person = gson.fromJson(FileReader("person.json"), Person::class.java)
	/* content of person.json
	{
	  "name" : "Kolineer",
	  "age" : 28,
	  "messages" : [ "To be Kotlin Master", "At JavaSampleAproach" ]
	}
	*/
	println(person2)
}

Check Result:


Person(name=Kolineer, age=26, messages=[Master Kotlin, At JavaSampleApproach])
Person(name=Kolineer, age=28, messages=[To be Kotlin Master, At JavaSampleAproach])

1.2 to JSON


package com.javasampleapproach.jsonstring

import com.google.gson.GsonBuilder

fun main(args: Array) {

	val gson = GsonBuilder().setPrettyPrinting().create()

	val person = Person("Kolineer", 27, listOf("I am Kotlin Learner", "At JavaSampleAproach"))
	val jsonPerson: String = gson.toJson(person)
	println(jsonPerson)
}

Check Result:


{
  "name": "Kolineer",
  "age": 27,
  "messages": [
    "I am Kotlin Learner",
    "At JavaSampleAproach"
  ]
}

2. List


package com.javasampleapproach.jsonstring

import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken

fun main(args: Array) {

	val jsonList = """[{"name": "Kolineer", "age": "26", "messages" : ["Master Kotlin","At JavaSampleApproach"]},
			{"name":"Kolineer Master","age":30,"messages":["I am Kotlin Master","still learning Kotlin at JavaSampleAproach"]}]"""

	val gson = GsonBuilder().setPrettyPrinting().create()
	
	println("=== List from JSON ===")
	var personList: List = gson.fromJson(jsonList, object : TypeToken>() {}.type)
	personList.forEach { println(it) }

	println("=== List to JSON ===")
	val jsonPersonList: String = gson.toJson(personList)
	println(jsonPersonList)
}

Check Result:


=== List from JSON ===
Person(name=Kolineer, age=26, messages=[Master Kotlin, At JavaSampleApproach])
Person(name=Kolineer Master, age=30, messages=[I am Kotlin Master, still learning Kotlin at JavaSampleAproach])
=== List to JSON ===
[
  {
    "name": "Kolineer",
    "age": 26,
    "messages": [
      "Master Kotlin",
      "At JavaSampleApproach"
    ]
  },
  {
    "name": "Kolineer Master",
    "age": 30,
    "messages": [
      "I am Kotlin Master",
      "still learning Kotlin at JavaSampleAproach"
    ]
  }
]

3. Map


package com.javasampleapproach.jsonstring

import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken

fun main(args: Array) {

	val json = """{"name": "Kolineer", "age": "26", "messages" : ["Master Kotlin","At JavaSampleApproach"]}"""
	val gson = GsonBuilder().setPrettyPrinting().create()

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

	println("=== Map to JSON ===")
	val jsonPersonMap: String = gson.toJson(personMap)
	println(jsonPersonMap)
}

Check Result:


=== Map from JSON ===
name=Kolineer
age=26
messages=[Master Kotlin, At JavaSampleApproach]
=== Map to JSON ===
{
  "name": "Kolineer",
  "age": "26",
  "messages": [
    "Master Kotlin",
    "At JavaSampleApproach"
  ]
}

4 thoughts on “Kotlin – How to convert Object to/from JSON by Gson with Kotlin language”

  1. Hello there! I know this is kind of off topic but I was wondering which blog platform
    are you using for this site? I’m getting fed up of WordPress because I’ve
    had issues with hackers and I’m looking at options for another
    platform. I would be great if you could point me in the direction of a
    good platform.

  2. Someone necessarily assist to make seriously articles I
    might state. This is the very first time I frequented your website
    page and so far? I amazed with the research you made to make this
    actual put up incredible. Magnificent job!

Leave a Reply

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