How to read a Json file with Kotlin

23.12.2018

Read a Json file with Kotlin

The article describes how to use Kotlin to read in a JSon file containing a date (LocalDate or LocalDateTime) and deserialize it into objects. In the example, a list of Json objects is read. For reading there are various options and numerous small projects at Github that do it. In this article, Jackson is used for reading and deserializing. In the example movies (Films) are imported, which contain the date (LocalDate or LocalDateTime), when they were watched at and where they were watched at (Provider).

Snippet to read the Json file

The following code snippet reads a Json file and then outputs the objects on the console. First the JacksonMapper is initialized and the JavaTimeModule is registered so that the date can be processed correctly.

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import java.io.File

fun main(args: Array<String>) {

    val mapper = jacksonObjectMapper()
    mapper.registerKotlinModule()
    mapper.registerModule(JavaTimeModule())

    val jsonString: String = File("./src/main/resources/films.json").readText(Charsets.UTF_8)
    val jsonTextList:List<Film> = mapper.readValue<List<Film>>(jsonString)
    for (film in jsonTextList) {
        println(film)
    }
}

Example Json file

The following json file contains some movies with the date when you watched it at which provider. You will also find an episode of a series with season number and episode number.

[
  {
    "name": "Terminator",
    "watchdate": "03.01.2018",
    "provider": "DVD"
  },
  {
    "name": "Rambo 2",
    "watchdate": "4.1.2018",
    "provider": "DVD"
  },
  {
    "name": "Rambo 3",
    "watchdate": "5.1.2018",
    "provider": "DVD"
  },
  {
    "name": "Tatort: Willkommen in Hamburg",
    "watchdate": "6.1.2018",
    "provider": "DVD"
  },
  {
    "name": "Bones",
    "watchdate": "8.12.2018",
    "provider": "Amazon Video",
    "seriesNo": "4",
    "episodeNo": "1"
  }
]

Film class

The Film class contains all the attributes, some of which are set over the constructor and others via setter. In addition, the @get annotation defines the date format (d.M.yyyy). If you want to deserialize a LocalDateTime object you can use the pattern (dd.MM.yyyy hh:mm:ss) for example.

import com.fasterxml.jackson.annotation.JsonFormat
import java.time.LocalDate


data class Film(val id: Long, val name: String, val provider: String) {


    companion object {
        const val NOT_AVAILABLE = 0
        const val NOT_A_SERIE = "N/A"
    }
    @get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "d.M.yyyy")
    var watchdate:LocalDate?=null

    var seriesNo: Int = NOT_AVAILABLE
    var episodeNo: Int = NOT_AVAILABLE
    var episodeName: String = NOT_A_SERIE

}

Maven dependencies for Jackson

In order for Jackson to be used, the following dependencies in the Maven POM file must be added. In jsr310 the processing of Date / Time is regulated. Therefore, this dependency must also exist.

<dependency> 
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.9.7</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.module</groupId>
  <artifactId>jackson-module-kotlin</artifactId>
  <version>2.9.7</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.module</groupId>
  <artifactId>jackson-module-kotlin</artifactId>
</dependency>

As I said, this is one way to read Json files. There are many others. However, projects with a REST interface often have Jackson as a dependency, so it makes sense to use Jackson to read in Json file.