Last active
March 26, 2018 02:33
-
-
Save akokshar/b5642c92daa989c5561687ae67d62652 to your computer and use it in GitHub Desktop.
annotations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlin.reflect.full.findAnnotation | |
| import kotlin.reflect.full.memberProperties | |
| @Target(AnnotationTarget.PROPERTY) | |
| annotation class JsonFileld | |
| interface JsonSerializable | |
| private fun JsonSerializable.serialize() = javaClass.kotlin.memberProperties.asSequence() | |
| .filter { | |
| it.findAnnotation<JsonFileld>() != null && it.get(this) != null | |
| } | |
| .joinToString(separator = ", ", prefix = "{",postfix = "}") { | |
| val value = it.get(this) | |
| when (value) { | |
| is Number -> "${it.name}: ${value.toString()}" | |
| else -> "${it.name}: \"${value}\"" | |
| } | |
| } | |
| inline private fun <reified T: JsonSerializable> String.deserialize() : T? { | |
| return null | |
| } | |
| data class File( | |
| @JsonFileld val type: Int = 0, | |
| @JsonFileld val name: String, | |
| @JsonFileld val content: String? = null | |
| ) : JsonSerializable | |
| fun main(args: Array<String>) { | |
| val f = File(type = 1, name = "filename 1") | |
| println("json f : ${f.serialize()}"); | |
| val f1 = File(type = 0, name = "filename 2", content = "This is content of the file") | |
| println("json f1: ${f1.serialize()}"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment