Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jackson to deserialize to Kotlin collections

Sample code what I want:

data class D(val a: String, val b: Int) val jsonStr = """[{"a": "value1", "b": 1}, {"a": "value2", "b":"2}]""" // what I need val listOfD: List<D> = jacksonObjectMapper().whatMethodAndParameter? 
like image 969
Marvin Avatar asked Oct 27 '15 12:10

Marvin


People also ask

What does Jackson module Kotlin do?

GitHub - FasterXML/jackson-module-kotlin: Module that adds support for serialization/deserialization of Kotlin (http://kotlinlang.org) classes and data classes. Module that adds support for serialization/deserialization of Kotlin (http://kotlinlang.org) classes and data classes.

What is Jackson deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.


1 Answers

With Jackson Kotlin Module current versions, if you import the full module package or the specific extension function you'll have all extension methods available. Such as:

import com.fasterxml.jackson.module.kotlin.*   val JSON = jacksonObjectMapper()  // keep around and re-use val myList: List<String> = JSON.readValue("""["a","b","c"]""") 

Therefore the Jackson Module for Kotlin will infer the the correct type and you do not need a TypeReference instance.

so your case (slightly renamed and fixed the data class, and JSON):

import com.fasterxml.jackson.module.kotlin.readValue  data class MyData(val a: String, val b: Int) val JSON = jacksonObjectMapper()    val jsonStr = """[{"a": "value1", "b": 1}, {"a": "value2", "b": 2}]""" val myList: List<MyData> = JSON.readValue(jsonStr) 

You can also use the form:

val myList = JSON.readValue<List<MyData>>(jsonStr) 

Without the import you will have an error because the extension function is not found.

like image 165
3 revs Avatar answered Sep 23 '22 23:09

3 revs