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://ozenero.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]

24 thoughts on “Kotlin – Convert Object to/from JSON with Jackson 2.x”

  1. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or
    something. I think that you could do with some pics to drive the message home a bit, but
    instead of that, this is wonderful blog.
    A great read. I will certainly be back.

  2. Hey very cool web site!! Man .. Excellent .. Amazing ..

    I will bookmark your web site and take the feeds also?
    I am glad to search out numerous useful information here within the put up, we need develop
    more techniques in this regard, thanks for sharing.
    . . . . .

  3. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours.

    It’s pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did,
    the net will be a lot more useful than ever before.

  4. It’s appropriate time to make a few plans for the future and it’s time
    to be happy. I have learn this publish and if I may just I wish to counsel you
    few fascinating issues or tips. Perhaps you can write subsequent articles regarding this article.
    I wish to read even more issues approximately it!

  5. Excellent web site. A lot of useful information here.
    I am sending it to several friends ans also sharing in delicious.
    And of course, thanks for your effort!

  6. Whoa! This blog looks just like my old one! It’s on a entirely different topic
    but it has pretty much the same layout and design. Superb choice of colors!

  7. Fantastic blog! Do you have any recommendations for aspiring writers?
    I’m hoping to start my own blog soon but I’m a little lost on everything.

    Would you propose starting with a free platform like WordPress
    or go for a paid option? There are so many options out
    there that I’m completely overwhelmed .. Any ideas? Thank you!

  8. This design is incredible! You most certainly know how to keep a
    reader amused. Between your wit and your videos, I was almost moved
    to start my own blog (well, almost…HaHa!) Fantastic job.
    I really enjoyed what you had to say, and more than that, how you
    presented it. Too cool!

  9. Hi there just wanted to give you a quick heads up and let you know a few
    of the pictures aren’t loading correctly. I’m not sure why but I think its a
    linking issue. I’ve tried it in two different internet browsers
    and both show the same results.

  10. It’s actually a nice and helpful piece of info. I’m happy
    that you shared this helpful info with us. Please keep us up to date like this.
    Thank you for sharing.

Leave a Reply

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