Request for Built-in toString(json=true) for Data Classes for Json Output


#1

As data classes are buit for holding data. It’s useful have built-in toString(json=true) for Data Classes for Json Output.


#2

Personally I vote no,
toString method should not have any serialization purpose, moreover serialization logic should be aware from the Kotlin core language.

I suggest you to implement the extension method

fun Any.toJson() = TODO("put your favourite library here")

#3

The problem with adding it to Kotlin is that now you’re including JSON logic directly in Kotlin.
Also, which implementation should be used, Gson, Jackson, … ?

This is a Jackson wrapper I use all the time:

fun Any.toJson(pretty: Boolean = false): String = if (pretty) Json.encodePrettily(this) else Json.encode(this)

inline fun <reified T : Any> String.fromJson(): T = Json.decodeValue(this, T::class.java)

inline fun <reified T : Any> String.fromJsonList(): List<T>  = mapper.readValue(this, mapper.typeFactory.constructCollectionType(List::class.java, T::class.java))

This allows me to just do:

val json = instanceOfMyClass.toJson()

or

val obj = """ { "foo" : "bar" } """.fromJson<MyClass>()

Simple enough to put those 3 lines of code in a library and simply include that lib every time you need JSON helper methods.


#4

Kotlin is not JS, so built-in JSON support in the language is not the best idea, however we are working on kotlin serialization approach that would let you convert Kotlin classes to a variety of formats and it does support JSON out-of-the-box. See here for details: https://github.com/Kotlin/kotlinx.serialization/ Please note, though, that it is in an early prototype stage.