Kotlin – Convert Object to/from JSON with Jackson 2.x

kotlin-convert-object-tofrom-json-jackson-2-x-feature-image

This tutorial shows you how to use Jackson 2.x 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/JSON url to Person(name:String,age:Int,messages:List) Kotlin Object, then convert Person object to JSON string/JSON file.

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.fasterxml.jackson.module</groupId>
	<artifactId>jackson-module-kotlin</artifactId>
	<version>2.8.8</version>
</dependency>

– import com.fasterxml.jackson.module.kotlin.*
– use ObjectMapper instance:


val mapper = jacksonObjectMapper()

// Json String/URL/File to Object
var person: Person = 
-> mapper.readValue(String)
-> mapper.readValue(URL)
-> mapper.readValue(File)

// Object to Json String/File
var jsonStr =
-> mapper.writeValueAsString(Person)
-> mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Person)
-> mapper.writeValue(File, Person)
-> mapper.writerWithDefaultPrettyPrinter().writeValue(File, Person)

III. Practice

0. Person Class


package com.javasampleapproach.jsonstring

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

1. Json String/URL/File to Object


package com.javasampleapproach.jsonstring

import com.fasterxml.jackson.module.kotlin.*
import java.net.URL
import java.io.File

fun main(args: Array) {

	val json = """{"name": "Kolineer", "age": "26", "messages" : ["message a","message b"]}"""
	val mapper = jacksonObjectMapper()

	println("=== JSON to Kotlin Object ===")
	println("1- read String")
	var person: Person = mapper.readValue(json)
	println(person)

	println("2- read URL")
	person = mapper.readValue(URL("https://grokonez.com/wp-content/uploads/2017/08/person.json"))
	println(person)

	println("3- read File")
	/* content of person.json
	{
	  "name" : "Kolineer",
	  "age" : 28,
	  "messages" : [ "message AA", "message BB" ]
	}
	*/
	person = mapper.readValue(File("person.json"))
	println(person)
}

Check Result:


=== JSON to Kotlin Object ===
1- read String
Person(name=Kolineer, age=26, messages=[message a, message b])
2- read URL
Person(name=Kolineer, age=27, messages=[message A, message B])
3- read File
Person(name=Kolineer, age=28, messages=[message AA, message BB])

2. Object to Json String/File


package com.javasampleapproach.jsonstring

import com.fasterxml.jackson.module.kotlin.*
import java.io.File

fun main(args: Array) {
	val mapper = jacksonObjectMapper()

	println("=== Kotlin Object to JSON ===")
	person = Person("Kolineer Master", 30, listOf("I am Kotlin Master", "still learning Kotlin"))
	
	println("1- String")
	var jsonStr = mapper.writeValueAsString(person)
	println(jsonStr)

	println("2- Formatted String")
	jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person)
	println(jsonStr)

	println("3- File -> manually check file for result")
	mapper.writerWithDefaultPrettyPrinter().writeValue(File("newPerson.json"), person)
}

Check Result:


=== Kotlin Object to JSON ===
1- String
{"name":"Kolineer Master","age":30,"messages":["I am Kotlin Master","still learning Kotlin"]}
2- Formatted String
{
  "name" : "Kolineer Master",
  "age" : 30,
  "messages" : [ "I am Kotlin Master", "still learning Kotlin" ]
}
3- File -> manually check file for result

IV. More Practice

1. Json array format to List


val jsonList =
"""[{"name": "Kolineer", "age": "26", "messages" : ["message a","message b"]},
{"name":"Kolineer Master","age":30,"messages":["I am Kotlin Master","still learning Kotlin"]}]"""

var personList: List = mapper.readValue(jsonList)
personList.forEach { println(it) }

Result:


Person(name=Kolineer, age=26, messages=[message a, message b])
Person(name=Kolineer Master, age=30, messages=[I am Kotlin Master, still learning Kotlin])

2. Json to Map


val json = """{"name": "Kolineer", "age": "26", "messages" : ["message a","message b"]}"""

var personMap: Map = mapper.readValue(json)
personMap.forEach { println(it) }

Result:


name=Kolineer
age=26
messages=[message a, message b]


By grokonez | August 29, 2017.

Last updated on April 12, 2021.



Related Posts


Got Something To Say:

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

*