Json to Kotlin Data Class

Is there a way and / or library to automatically create a Kotlin data class from Json, how does it work in Scala Json.Spray?

Something like that:

data class User(id: Int, name: String) class DataClassFactory(val json: String) { fun getUser(): User { //some reflection return User(10, "Kirill") } } fun main(args: Array<String>): Unit { val json = "{id: 10, name: Kirill}" val usr = DataClassFactory(json).getUser() println(usr) } 
+6
source share
5 answers

You can use the Jackson module for Kotlin to serialize / deserialize easily from any format supported by Jackson (including JSON). This is the easiest way and supports Kotlin data classes without annotations. See https://github.com/FasterXML/jackson-module-kotlin for a module that includes the latest information for use with Maven and Gradle (you can conclude that IVY and load the JAR from the Maven repository)

There are alternatives such as Boon, but it does not have specific support for Kotlin (this is usually a problem with the lack of a default constructor) and uses some insecure direct access to the JVM inner classes for performance. At the same time, it may fall on some virtual machines, and in those cases when you extend Boon from Kotlin using a special serializer / deserializer, he makes assumptions about classes that are not true in Kotlin (for example, the String class) saw a dump of the kernel. Boon brightens quickly, just be careful with these problems and check first before use.

(note: I am the creator of the Jackson-Kotlin module)

+5
source

It is very clean and easy in Kotlin.

 import com.fasterxml.jackson.module.kotlin.* data class User(val id: Int, val name: String) fun main(args: Array<String>) { val mapper = jacksonObjectMapper() val json = """{"id": 10, "name": "Kirill"}""" val user = mapper.readValue<User>(json) println(user) } 

produces this conclusion:

 User(id=10, name=Kirill) 

you need to add this to your pom.xml

  <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-kotlin</artifactId> <version>2.6.3-4</version> </dependency> 
+4
source

Why not use Jackson or any other serializer? It should work.

+1
source

How about this? This is a translator that translates a JSON string into a kotlin data class, it does it through a plugin, see next a demo usage https://plugins.jetbrains.com/plugin/9960-jsontokotlinclass

0
source

http://www.json2kotlin.com converts your json response into kotlin data classes online, without having to install any plugin. In addition, you can create gson annotations. (Disclosure: I created this utility)

0
source

Source: https://habr.com/ru/post/974937/


All Articles