Introduction
It seems that many backends that provide a REST API end up being enhanced proxies that move JSON from one place to another. It is especially true if you are trying to keep those backends as simple as possible. Having the right tools to parse and produce JSON can thus make a big difference in keeping the code tidy and compact.
Here we’re going to look at ways to convert JSON string, JSON file, JSON url into Object.
What is Jackson
Jackson is a library that helps us to serialise and deserialise data into a format that best suits our needs. Jackson is used widely in Java applications and now has a fantastic Kotlin-compatible module.
Add Jackson to your Kotlin project
Adding Jackson to your Kotlin project is simple. The whole process can be divided into the following two steps,
- Add Dependency
- Use Jackson
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:
com.fasterxml.jackson.module jackson-module-kotlin 2.8.8
- Jar:
Go to Maven Repository and download .jar file.
Use Jackson
Anywhere you want to make Jackson work, just follow two steps:
- import fasterxml.jackson.module.kotlin.*
- use ObjectMapper instance like below:
val mapper = jacksonObjectMapper()
// Json String/URL/File to Object
var person: Person =
-> mapper.readValue(String) // parse from string
-> mapper.readValue(URL) // parse from URL
-> mapper.readValue(File) // parse from file
Where ‘Person’ is a plain data class which maps the json contents.
Summary
Jackson is a very powerful library in which working with JSON becomes very easy while keeping a good amount of type safety in the process. In this article we have learned how to set up Jackson in a Kotlin project and serialize the JSON objects from String, URL & file to plain data objects in Kotlin.