kotlin-convert-json-to-object-feature-image

Kotlin – Convert JSON to Object and vice versa using Jackson

In this tutorial, we’re gonna look at way to convert JSON string, JSON file, JSON url into Object, Array, Map and do the opposite: convert Object to JSON String in Kotlin using Jackson library.

Related Posts:
Kotlin List & Mutable List tutorial with examples
Kotlin – parse JSON to object & convert object to JSON using Gson
Kotlin – Convert object of a Data Class to another Data Class object


Add Jackson to your Kotlin project

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

Add Dependency

There are three ways to add Jackson library to our Kotlin project:

  • Gradle/Android:
  • dependencies {
      implementation 'com.fasterxml.jackson.module:jackson-module-kotlin:2.8.+'
    }
    
  • Maven:
  • <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-kotlin</artifactId>
      <version>2.8.8</version>
    </dependency>
    
  • Jar:
  • Go to Maven Repository and download .jar file.

Use Jackson

Anywhere you want to make Jackson work, just follow two steps:
– import com.fasterxml.jackson.module.kotlin.*
– use ObjectMapper instance like this:

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 jsonString =
-> mapper.writeValueAsString(Person)
-> mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Person)
-> mapper.writeValue(File, Person)
-> mapper.writerWithDefaultPrettyPrinter().writeValue(File, Person)

Create a Kotlin Data Class

Let’s create a plain Class called Person in Person.kt.

package com.bezkoder.kotlin.json
 
data class Person(val name: String, val age: Int, val messages: List) {
}

Convert JSON String/URL/File to Object

The example shows you way to use ObjectMapper.readValue() function to:

  • convert JSON String to Kotlin object
  • convert JSON URL to Kotlin object
  • convert JSON file to Kotlin object

app.kt

package com.bezkoder.kotlin.json
 
import com.fasterxml.jackson.module.kotlin.*
import java.net.URL
import java.io.File
 
fun main(args: Array<String>) {
 
  val json = """{"name": "bezkoder", "age": "26", "messages" : ["hello","becoming zKoder"]}"""
  val mapper = jacksonObjectMapper()
 
  println("=== JSON to Kotlin Object ===")
  println("1- read String")
  var person: Person = mapper.readValue<Person>(json)
  println(person)
 
  println("2- read URL")
  person = mapper.readValue<Person>(URL("http://url-to-person.json"))
  println(person)
 
  println("3- read File")
  /* content of person.json
  {
    "name" : "bezkoder",
    "age" : 28,
    "messages" : [ "Great!", "Im zKoder" ]
  }
  */
  person = mapper.readValue<Person>(File("person.json"))
  println(person)
}

Run the program, the result in console looks like this-

=== JSON to Kotlin Object ===
1- read String
Person(name=bezkoder, age=26, messages=[hello, becoming zKoder])
2- read URL
Person(name=bezkoder, age=27, messages=[grow, up])
3- read File
Person(name=bezkoder, age=28, messages=[Great!, Im zKoder])

Convert Object to JSON String/File

The example shows you how to:

  • convert Object to JSON String using writeValueAsString() function (with or without writerWithDefaultPrettyPrinter() to apply Pretty Printer)
  • convert Object to JSON File using writeValue() function

app.kt

package com.bezkoder.kotlin.json
 
import com.fasterxml.jackson.module.kotlin.*
import java.io.File

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

  println("=== Kotlin Object to JSON ===")
  person = Person("bezkoder 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)
}

Now check the result:

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

Convert JSON array format to List in Kotlin

We can also use readValue() function to get a Kotlin List object from a JSON String array:

import com.fasterxml.jackson.module.kotlin.*

val jsonList =
"""[{"name": "bezkoder", "age": "26", "messages" : ["hello","becoming zKoder"]},
{"name":"bezkoder Master","age":30,"messages":["I am Kotlin Master","still learning Kotlin"]}]"""

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

The result will look like this.

Person(name=bezkoder, age=26, messages=[hello, becoming zKoder])
Person(name=bezkoder Master, age=30, messages=[I am Kotlin Master, still learning Kotlin])

Convert JSON array format to Map in Kotlin

readValue() function can help us to get a Kotlin Map object from a JSON Map format:

import com.fasterxml.jackson.module.kotlin.*

val json = """{"name": "bezkoder", "age": "26", "messages" : ["Great!","Im zKoder"]}"""
 
val mapper = jacksonObjectMapper() 
var personMap: Map = mapper.readValue(json)
personMap.forEach { println(it) }

Check the result, you can see:

name=bezkoder
age=26
messages=[Great!, Im zKoder]

Conclusion

Today we’re known how to convert JSON string/file/url into many type of Kotlin Object such as Data Class, List, Map and do the opposite: convert Object, Array, Map to JSON String using Jackson.

The steps can be summarized as:

  • Add Jackson library
  • Define Kolin Data Class
  • Use ObjectMapper.readValue() or ObjectMapper.writeValueAsString()
  • Use additional package writerWithDefaultPrettyPrinter() function to get pretty JSON

Happy learning! See you again.

Further Reading

One thought to “Kotlin – Convert JSON to Object and vice versa using Jackson”

Leave a Reply

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