Skip to content

Instantly share code, notes, and snippets.

@slaykovsky slaykovsky/main.kt
Created Apr 2, 2018

Embed
What would you like to do?
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.memberProperties
@Target(AnnotationTarget.PROPERTY)
annotation class JsonFileId
interface JsonSerializable
fun JsonSerializable.serialize(): String {
fun s(x: Any?): String {
return when (x) {
is String -> "\"$x\""
is Number -> x.toString()
is Boolean -> x.toString()
is Array<*> -> x
.map { s(it) }
.filter { it.isNotEmpty() }
.joinToString(
prefix = "[",
separator = ", ",
postfix = "]"
)
is JsonSerializable -> x.serialize()
null -> "null"
else -> ""
}
}
return this.javaClass.kotlin.memberProperties.asSequence()
.filter { it.findAnnotation<JsonFileId>() != null }
.joinToString(
prefix = "{",
separator = ", ",
postfix = "}") {
buildString {
append(it.name)
append(": ")
append(s(it.get(this@serialize)))
}
}
}
data class Govno(
@JsonFileId val name: String,
@JsonFileId val weigth: Int,
@JsonFileId val packs: Array<String>,
@JsonFileId val rot: Boolean) : JsonSerializable
fun main(args: Array<String>) {
val govno = Govno("govno", 42,
Array<String>(5, { it.toString() }),
true)
println(govno.serialize())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.