Created
April 1, 2018 16:22
-
-
Save akokshar/3ec755327a9a860f5e0ccc55e80c7066 to your computer and use it in GitHub Desktop.
json serializer, deserealizer lexer
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.coroutines.experimental.buildIterator | |
| import kotlin.reflect.KProperty1 | |
| import kotlin.reflect.full.findAnnotation | |
| import kotlin.reflect.full.memberProperties | |
| @Target(AnnotationTarget.PROPERTY) | |
| annotation class JsonFileld | |
| interface JsonSerializable | |
| private fun serializeValue(value: Any?): String { | |
| return when (value) { | |
| null -> "null" | |
| is Boolean -> if (value) "true" else "false" | |
| is String -> "\"${value.toString()}\"" | |
| is Array<*> -> value | |
| .map{ | |
| serializeValue(it) | |
| } | |
| .filter { | |
| it.length > 0 | |
| } | |
| .joinToString(prefix = "[", separator = ",", postfix = "]") | |
| is Number -> value.toString() | |
| is JsonSerializable -> value.serialize() | |
| else -> "" | |
| } | |
| } | |
| fun JsonSerializable.serialize(): String { | |
| return this.javaClass.kotlin.memberProperties.asSequence() | |
| .filter { | |
| it.findAnnotation<JsonFileld>() != null | |
| } | |
| .joinToString(prefix = "{", separator = ", ", postfix = "}") { | |
| buildString { | |
| append(it.name) | |
| append(": ") | |
| append(serializeValue(it.get(this@serialize))) | |
| } | |
| } | |
| } | |
| inline fun <reified T: JsonSerializable> String.deserialize() : T? { | |
| val tokens = split(regex = Regex("((?<=[\\]\\[}{,:])|(?=[\\]\\[}{,:]))")).asSequence() | |
| .map { | |
| it.trim() | |
| } | |
| .filter { | |
| it.length > 0 | |
| } | |
| .joinToString { | |
| "'$it'" | |
| } | |
| println("$tokens") | |
| return null | |
| } | |
| data class File( | |
| @JsonFileld val type: Int = 0, | |
| @JsonFileld val name: String, | |
| @JsonFileld val visible: Boolean = true, | |
| @JsonFileld val flags: Array<Int>? = arrayOf(1,2,3), | |
| 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") | |
| val f1_json = f1.serialize() | |
| println("json f1: ${f1_json}"); | |
| f1_json.deserialize<File>() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment