├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── kotlin │ │ └── kia │ │ └── jkid │ │ ├── exercise │ │ └── DateFormat.kt │ │ ├── Main.kt │ │ ├── Annotations.kt │ │ ├── Util.kt │ │ ├── deserialization │ │ ├── Parser.kt │ │ ├── ClassInfoCache.kt │ │ ├── Deserializer.kt │ │ └── Lexer.kt │ │ ├── ValueSerializers.kt │ │ └── serialization │ │ └── Serializer.kt └── test │ └── kotlin │ ├── deserialization │ ├── BookExample.kt │ ├── LexerTest.kt │ ├── ParserTest.kt │ └── DeserializerTest.kt │ ├── examples │ ├── testUtil.kt │ ├── _2BookExample.kt │ ├── _1PersonExample.kt │ ├── _3AnnotationsExample.kt │ ├── _5DeserializeInterfaceExample.kt │ ├── _4RuleExample.kt │ └── _6DateSerializerExample.kt │ ├── exercise │ ├── Map.kt │ └── DateFormatAnnotation.kt │ └── serialization │ └── SerializerTest.kt ├── settings.gradle.kts ├── .idea ├── kotlinc.xml ├── vcs.xml ├── .gitignore ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml └── gradle.xml ├── .gitignore ├── LICENSE ├── gradlew.bat ├── README.md └── gradlew /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kotlin/kotlin-in-action-2e-jkid/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/exercise/DateFormat.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.exercise 2 | 3 | @Target(AnnotationTarget.PROPERTY) 4 | annotation class DateFormat(val format: String) 5 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenCentral() 4 | gradlePluginPortal() 5 | } 6 | 7 | } 8 | rootProject.name = "jkid-updated" 9 | 10 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/Main.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid 2 | 3 | fun main(args: Array) { 4 | println("Hello World!") 5 | 6 | // Try adding program arguments via Run/Debug configuration. 7 | // Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html. 8 | println("Program arguments: ${args.joinToString()}") 9 | } -------------------------------------------------------------------------------- /src/test/kotlin/deserialization/BookExample.kt: -------------------------------------------------------------------------------- 1 | package deserialization 2 | 3 | import kia.jkid.deserialization.deserialize 4 | 5 | data class Author(val name: String) 6 | data class Book(val title: String, val author: Author) 7 | 8 | fun main(args: Array) { 9 | val json = """{"title": "Catch-22", "author": {"name": "J. Heller"}}""" 10 | println(deserialize(json)) 11 | } 12 | -------------------------------------------------------------------------------- /src/test/kotlin/examples/testUtil.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.jsonSerializerTest 2 | 3 | import kia.jkid.deserialization.deserialize 4 | import kia.jkid.serialization.serialize 5 | import kotlin.test.assertEquals 6 | 7 | inline fun testJsonSerializer(value: T, json: String) { 8 | 9 | assertEquals(json, serialize(value)) 10 | 11 | assertEquals(value, deserialize(json)) 12 | } -------------------------------------------------------------------------------- /src/test/kotlin/examples/_2BookExample.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.innerObjectTest 2 | 3 | import kia.jkid.examples.jsonSerializerTest.testJsonSerializer 4 | import kotlin.test.Test 5 | 6 | data class Author(val fullName: String) 7 | data class Book(val name: String, val authors: List) 8 | 9 | 10 | class BookTest { 11 | @Test fun test() = testJsonSerializer( 12 | value = Book("Lord of the Rings", listOf(Author("J.R.R.Tolkien"))), 13 | json = """{"authors": [{"fullName": "J.R.R.Tolkien"}], "name": "Lord of the Rings"}""" 14 | ) 15 | } -------------------------------------------------------------------------------- /src/test/kotlin/examples/_1PersonExample.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.simple 2 | 3 | import kia.jkid.deserialization.deserialize 4 | import kia.jkid.serialization.serialize 5 | import kotlin.test.Test 6 | import kotlin.test.assertEquals 7 | 8 | data class Person(val name: String, val age: Int) 9 | 10 | class PersonTest { 11 | @Test fun test() { 12 | val person = Person("Alice", 29) 13 | val json = """{"age": 29, "name": "Alice"}""" 14 | 15 | assertEquals(json, serialize(person)) 16 | assertEquals(person, deserialize(json)) 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/kotlin/examples/_3AnnotationsExample.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.annotationsTest 2 | 3 | import kia.jkid.JsonExclude 4 | import kia.jkid.JsonName 5 | import kia.jkid.examples.jsonSerializerTest.testJsonSerializer 6 | import kotlin.test.Test 7 | 8 | data class Person( 9 | @JsonName(name = "first_name") val firstName: String, 10 | @JsonExclude val age: Int? = null 11 | ) 12 | 13 | class AnnotationsTest { 14 | @Test fun test() = testJsonSerializer( 15 | value = Person("Alice"), 16 | json = """{"first_name": "Alice"}""" 17 | ) 18 | } -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/Annotations.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid 2 | 3 | import kotlin.reflect.KClass 4 | 5 | @Target(AnnotationTarget.PROPERTY) 6 | annotation class JsonExclude 7 | 8 | @Target(AnnotationTarget.PROPERTY) 9 | annotation class JsonName(val name: String) 10 | 11 | interface ValueSerializer { 12 | fun toJsonValue(value: T): Any? 13 | fun fromJsonValue(jsonValue: Any?): T 14 | } 15 | 16 | @Target(AnnotationTarget.PROPERTY) 17 | annotation class DeserializeInterface(val targetClass: KClass) 18 | 19 | @Target(AnnotationTarget.PROPERTY) 20 | annotation class CustomSerializer(val serializerClass: KClass>) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/modules.xml 9 | .idea/jarRepositories.xml 10 | .idea/compiler.xml 11 | .idea/libraries/ 12 | *.iws 13 | *.iml 14 | *.ipr 15 | out/ 16 | !**/src/main/**/out/ 17 | !**/src/test/**/out/ 18 | 19 | ### Eclipse ### 20 | .apt_generated 21 | .classpath 22 | .factorypath 23 | .project 24 | .settings 25 | .springBeans 26 | .sts4-cache 27 | bin/ 28 | !**/src/main/**/bin/ 29 | !**/src/test/**/bin/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | 41 | ### Mac OS ### 42 | .DS_Store -------------------------------------------------------------------------------- /src/test/kotlin/examples/_5DeserializeInterfaceExample.kt: -------------------------------------------------------------------------------- 1 | package examples 2 | 3 | import kia.jkid.DeserializeInterface 4 | import kia.jkid.examples.jsonSerializerTest.testJsonSerializer 5 | import kotlin.test.Test 6 | 7 | interface Company { 8 | val name: String 9 | } 10 | 11 | data class CompanyImpl(override val name: String) : Company 12 | 13 | data class Person( 14 | val name: String, 15 | @DeserializeInterface(CompanyImpl::class) val company: Company 16 | ) 17 | 18 | class DeserializeInterfaceTest { 19 | @Test fun test() = testJsonSerializer( 20 | value = Person("Alice", CompanyImpl("JetBrains")), 21 | json = """{"company": {"name": "JetBrains"}, "name": "Alice"}""" 22 | ) 23 | } -------------------------------------------------------------------------------- /src/test/kotlin/exercise/Map.kt: -------------------------------------------------------------------------------- 1 | package exercise 2 | 3 | import kotlin.test.Test 4 | import kia.jkid.deserialization.deserialize 5 | import kia.jkid.serialization.serialize 6 | import kotlin.test.Ignore 7 | import kotlin.test.assertEquals 8 | 9 | data class BookStore(val bookPrice: Map) 10 | 11 | @Ignore 12 | class MapTest { 13 | private val bookStore = BookStore(mapOf("Catch-22" to 10.92, "The Lord of the Rings" to 11.49)) 14 | private val json = """{"bookPrice": {"Catch-22": 10.92, "The Lord of the Rings": 11.49}}""" 15 | 16 | @Test fun testSerialization() { 17 | println(serialize(bookStore)) 18 | assertEquals(json, serialize(bookStore)) 19 | } 20 | 21 | @Test fun testDeserialization() { 22 | assertEquals(bookStore, deserialize(json)) 23 | } 24 | } -------------------------------------------------------------------------------- /src/test/kotlin/examples/_4RuleExample.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.rule 2 | 3 | import kia.jkid.serialization.serialize 4 | import org.junit.jupiter.api.io.TempDir 5 | import java.nio.file.Path 6 | import kotlin.io.path.createFile 7 | import kotlin.io.path.readText 8 | import kotlin.io.path.writeText 9 | import kotlin.test.Test 10 | import kotlin.test.assertEquals 11 | 12 | data class Person(val name: String, val age: Int) 13 | 14 | class WriteJsonToFileTest { 15 | 16 | @Test fun testUsingTempFolder(@TempDir folder: Path) { 17 | val person = Person("Alice", 29) 18 | val json = """{"age": 29, "name": "Alice"}""" 19 | val jsonFile = (folder.resolve("person.json")).createFile() 20 | jsonFile.writeText(serialize(person)) 21 | assertEquals(json, jsonFile.readText()) 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/kotlin/exercise/DateFormatAnnotation.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.exercise 2 | 3 | import kia.jkid.deserialization.deserialize 4 | import kia.jkid.serialization.serialize 5 | import java.text.SimpleDateFormat 6 | import java.util.* 7 | import kotlin.test.Ignore 8 | import kotlin.test.Test 9 | import kotlin.test.assertEquals 10 | 11 | data class Person( 12 | val name: String, 13 | @DateFormat("dd-MM-yyyy") val birthDate: Date 14 | ) 15 | 16 | @Ignore 17 | class DateFormatTest { 18 | private val value = Person("Alice", SimpleDateFormat("dd-MM-yyyy").parse("13-02-1987")) 19 | private val json = """{"birthDate": "13-02-1987", "name": "Alice"}""" 20 | 21 | @Test fun testSerialization() { 22 | assertEquals(json, serialize(value)) 23 | } 24 | 25 | @Test fun testDeserialization() { 26 | assertEquals(value, deserialize(json)) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/Util.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid 2 | 3 | import kotlin.reflect.KType 4 | import kotlin.reflect.typeOf 5 | 6 | fun Iterable.joinToStringBuilder( 7 | stringBuilder: StringBuilder, 8 | separator: CharSequence = ", ", 9 | prefix: CharSequence = "", 10 | postfix: CharSequence = "", 11 | limit: Int = -1, 12 | truncated: CharSequence = "...", 13 | callback: ((T) -> Unit)? = null 14 | ): StringBuilder { 15 | return joinTo(stringBuilder, separator, prefix, postfix, limit, truncated) { 16 | if (callback == null) return@joinTo it.toString() 17 | callback(it) 18 | "" 19 | } 20 | } 21 | 22 | fun KType.isPrimitiveOrString(): Boolean { 23 | val types = setOf( 24 | typeOf(), 25 | typeOf(), 26 | typeOf(), 27 | typeOf(), 28 | typeOf(), 29 | typeOf(), 30 | typeOf(), 31 | typeOf(), 32 | typeOf(), 33 | ) 34 | return this in types 35 | } -------------------------------------------------------------------------------- /src/test/kotlin/examples/_6DateSerializerExample.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.examples.customSerializerTest 2 | 3 | import kia.jkid.CustomSerializer 4 | import kia.jkid.ValueSerializer 5 | import kia.jkid.examples.jsonSerializerTest.testJsonSerializer 6 | import java.text.SimpleDateFormat 7 | import java.util.* 8 | import kotlin.test.Test 9 | 10 | object DateSerializer : ValueSerializer { 11 | private val dateFormat = SimpleDateFormat("dd-mm-yyyy") 12 | 13 | override fun toJsonValue(value: Date): Any? = 14 | dateFormat.format(value) 15 | 16 | override fun fromJsonValue(jsonValue: Any?): Date = 17 | dateFormat.parse(jsonValue as String) 18 | } 19 | 20 | data class Person( 21 | val name: String, 22 | @CustomSerializer(DateSerializer::class) val birthDate: Date 23 | ) 24 | 25 | class DateSerializerTest { 26 | @Test fun test() = testJsonSerializer( 27 | value = Person("Alice", SimpleDateFormat("dd-mm-yyyy").parse("13-02-1987")), 28 | json = """{"birthDate": "13-02-1987", "name": "Alice"}""" 29 | ) 30 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Kotlin in Action Authors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/test/kotlin/serialization/SerializerTest.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.serialization 2 | 3 | import kia.jkid.deserialization.* 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | 7 | class SerializerTest { 8 | @Test fun testSimple() { 9 | val result = serialize(SingleStringProp("x")) 10 | assertEquals("""{"s": "x"}""", result) 11 | } 12 | 13 | @Test fun testTwoInts() { 14 | val result = serialize(TwoIntProp(1, 2)) 15 | assertEquals("""{"i1": 1, "i2": 2}""", result) 16 | } 17 | 18 | @Test fun testTwoBools() { 19 | val result = serialize(TwoBoolProp(true, false)) 20 | assertEquals("""{"b1": true, "b2": false}""", result) 21 | } 22 | 23 | @Test fun testObject() { 24 | val result = serialize(SingleObjectProp(SingleStringProp("x"))) 25 | assertEquals("""{"o": {"s": "x"}}""", result) 26 | } 27 | 28 | @Test fun testList() { 29 | val result = serialize(SingleListProp(listOf("a", "b"))) 30 | assertEquals("""{"o": ["a", "b"]}""", result) 31 | } 32 | 33 | @Test fun testListOfNull() { 34 | val result = serialize(SingleListProp(listOf(null, "b"))) 35 | assertEquals("""{"o": [null, "b"]}""", result) 36 | } 37 | 38 | @Test fun testJsonName() { 39 | val result = serialize(SingleAnnotatedStringProp("x")) 40 | assertEquals("""{"q": "x"}""", result) 41 | } 42 | 43 | @Test fun testCustomSerializer() { 44 | val result = serialize(SingleCustomSerializedProp(1)) 45 | assertEquals("""{"x": "ONE"}""", result) 46 | } 47 | 48 | @Test fun testEscapeSequences() { 49 | val result = serialize(SingleStringProp("\\\"")) 50 | assertEquals("""{"s": "\\\""}""", result) 51 | } 52 | 53 | @Test fun testJsonExclude() { 54 | val result = serialize(TwoPropsOneExcluded("foo", "bar")) 55 | assertEquals("""{"s": "foo"}""", result) 56 | } 57 | } -------------------------------------------------------------------------------- /src/test/kotlin/deserialization/LexerTest.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import java.io.StringReader 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | import kotlin.test.assertFailsWith 7 | import kotlin.test.assertNull 8 | 9 | class LexerTest { 10 | @Test fun testTrivial() { 11 | verifyTokens(",", Token.COMMA) 12 | } 13 | 14 | @Test fun testWhitespace() { 15 | verifyTokens(" , \t", Token.COMMA) 16 | } 17 | 18 | @Test fun testAllSingleChars() { 19 | verifyTokens("[]{}:,", Token.LBRACKET, Token.RBRACKET, Token.LBRACE, Token.RBRACE, Token.COLON, Token.COMMA) 20 | } 21 | 22 | @Test fun testBoolean() { 23 | verifyTokens("true", Token.TRUE) 24 | verifyTokens("false", Token.FALSE) 25 | } 26 | 27 | @Test fun testNull() { 28 | verifyTokens("null", Token.NullValue) 29 | } 30 | 31 | @Test fun testEscapeSequences() { 32 | verifyTokens(""""\\"""", Token.StringValue("\\")) 33 | verifyTokens(""""\""""", Token.StringValue("\"")) 34 | verifyTokens(""""\/"""", Token.StringValue("/")) 35 | verifyTokens(""""\n"""", Token.StringValue("\n")) 36 | verifyTokens(""""\u0041"""", Token.StringValue("A")) 37 | } 38 | 39 | 40 | @Test fun testNullMalformed() { 41 | verifyMalformed("nulll") 42 | } 43 | 44 | @Test fun testString() { 45 | verifyTokens("\"abc\"", Token.StringValue("abc")) 46 | } 47 | 48 | @Test fun testInt() { 49 | verifyTokens("0", Token.LongValue(0)) 50 | } 51 | 52 | @Test fun testNegativeInt() { 53 | verifyTokens("-1", Token.LongValue(-1)) 54 | } 55 | 56 | @Test fun testDouble() { 57 | verifyTokens("0.0", Token.DoubleValue(0.0)) 58 | } 59 | 60 | @Test fun testNegativeDouble() { 61 | verifyTokens("-1.0", Token.DoubleValue(-1.0)) 62 | } 63 | 64 | private fun verifyTokens(text: String, vararg tokens: Token) { 65 | val lexer = Lexer(StringReader(text)) 66 | for (expectedToken in tokens) { 67 | assertEquals(expectedToken, lexer.nextToken()) 68 | } 69 | assertNull(lexer.nextToken(), "Too many tokens") 70 | } 71 | 72 | private fun verifyMalformed(text: String) { 73 | assertFailsWith { 74 | Lexer(StringReader(text)).nextToken() 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/deserialization/Parser.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import java.io.Reader 4 | 5 | class Parser(reader: Reader, val rootObject: JsonObject) { 6 | private val lexer = Lexer(reader) 7 | 8 | fun parse() { 9 | expect(Token.LBRACE) 10 | parseObjectBody(rootObject) 11 | if (lexer.nextToken() != null) { 12 | throw IllegalArgumentException("Too many tokens") 13 | } 14 | } 15 | 16 | private fun parseObjectBody(jsonObject: JsonObject) { 17 | parseCommaSeparated(Token.RBRACE) { token -> 18 | if (token !is Token.StringValue) { 19 | throw MalformedJSONException("Unexpected token $token") 20 | } 21 | 22 | val propName = token.value 23 | expect(Token.COLON) 24 | parsePropertyValue(jsonObject, propName, nextToken()) 25 | } 26 | } 27 | 28 | private fun parseArrayBody(currentObject: JsonObject, propName: String) { 29 | parseCommaSeparated(Token.RBRACKET) { token -> 30 | parsePropertyValue(currentObject, propName, token) 31 | } 32 | } 33 | 34 | private fun parseCommaSeparated(stopToken: Token, body: (Token) -> Unit) { 35 | var expectComma = false 36 | while (true) { 37 | var token = nextToken() 38 | if (token == stopToken) return 39 | if (expectComma) { 40 | if (token != Token.COMMA) throw MalformedJSONException("Expected comma") 41 | token = nextToken() 42 | } 43 | 44 | body(token) 45 | 46 | expectComma = true 47 | } 48 | } 49 | 50 | private fun parsePropertyValue(currentObject: JsonObject, propName: String, token: Token) { 51 | when (token) { 52 | is Token.ValueToken -> 53 | currentObject.setSimpleProperty(propName, token.value) 54 | 55 | Token.LBRACE -> { 56 | val childObj = currentObject.createObject(propName) 57 | parseObjectBody(childObj) 58 | } 59 | 60 | Token.LBRACKET -> { 61 | val childObj = currentObject.createArray(propName) 62 | parseArrayBody(childObj, propName) 63 | } 64 | 65 | else -> 66 | throw MalformedJSONException("Unexpected token $token") 67 | } 68 | } 69 | 70 | private fun expect(token: Token) { 71 | if (lexer.nextToken() != token) { 72 | throw IllegalArgumentException("$token expected") 73 | } 74 | } 75 | 76 | private fun nextToken(): Token = lexer.nextToken() ?: throw IllegalArgumentException("Premature end of data") 77 | } 78 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/ValueSerializers.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid 2 | 3 | import kia.jkid.deserialization.JKidException 4 | import kotlin.reflect.KType 5 | import kotlin.reflect.typeOf 6 | 7 | fun serializerForBasicType(type: KType): ValueSerializer { 8 | assert(type.isPrimitiveOrString()) { "Expected primitive type or String: $type" } 9 | return serializerForType(type)!! 10 | } 11 | 12 | fun serializerForType(type: KType): ValueSerializer? = 13 | when (type) { 14 | typeOf() -> ByteSerializer 15 | typeOf() -> ShortSerializer 16 | typeOf() -> IntSerializer 17 | typeOf() -> LongSerializer 18 | typeOf() -> FloatSerializer 19 | typeOf() -> DoubleSerializer 20 | typeOf() -> BooleanSerializer 21 | typeOf(), 22 | typeOf() -> StringSerializer 23 | else -> null 24 | } 25 | 26 | private fun Any?.expectNumber(): Number { 27 | if (this !is Number) throw JKidException("Expected number, was: $this") 28 | return this 29 | } 30 | 31 | object ByteSerializer : ValueSerializer { 32 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toByte() 33 | override fun toJsonValue(value: Byte) = value 34 | } 35 | 36 | object ShortSerializer : ValueSerializer { 37 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toShort() 38 | override fun toJsonValue(value: Short) = value 39 | } 40 | 41 | object IntSerializer : ValueSerializer { 42 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toInt() 43 | override fun toJsonValue(value: Int) = value 44 | } 45 | 46 | object LongSerializer : ValueSerializer { 47 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toLong() 48 | override fun toJsonValue(value: Long) = value 49 | } 50 | 51 | object FloatSerializer : ValueSerializer { 52 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toFloat() 53 | override fun toJsonValue(value: Float) = value 54 | } 55 | 56 | object DoubleSerializer : ValueSerializer { 57 | override fun fromJsonValue(jsonValue: Any?) = jsonValue.expectNumber().toDouble() 58 | override fun toJsonValue(value: Double) = value 59 | } 60 | 61 | object BooleanSerializer : ValueSerializer { 62 | override fun fromJsonValue(jsonValue: Any?): Boolean { 63 | if (jsonValue !is Boolean) throw JKidException("Expected boolean, was: $jsonValue") 64 | return jsonValue 65 | } 66 | 67 | override fun toJsonValue(value: Boolean) = value 68 | } 69 | 70 | object StringSerializer : ValueSerializer { 71 | override fun fromJsonValue(jsonValue: Any?): String? { 72 | if (jsonValue !is String?) throw JKidException("Expected string, was: $jsonValue") 73 | return jsonValue 74 | } 75 | 76 | override fun toJsonValue(value: String?) = value 77 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/serialization/Serializer.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.serialization 2 | 3 | import kia.jkid.CustomSerializer 4 | import kia.jkid.JsonExclude 5 | import kia.jkid.JsonName 6 | import kia.jkid.ValueSerializer 7 | import kia.jkid.joinToStringBuilder 8 | import kotlin.reflect.KClass 9 | import kotlin.reflect.KProperty 10 | import kotlin.reflect.KProperty1 11 | import kotlin.reflect.full.createInstance 12 | import kotlin.reflect.full.findAnnotation 13 | import kotlin.reflect.full.memberProperties 14 | 15 | fun serialize(obj: Any): String = buildString { serializeObject(obj) } 16 | 17 | /* the first implementation discussed in the book */ 18 | private fun StringBuilder.serializeObjectWithoutAnnotation(obj: Any) { 19 | val kClass = obj::class as KClass 20 | val properties = kClass.memberProperties 21 | 22 | properties.joinToStringBuilder(this, prefix = "{", postfix = "}") { prop -> 23 | serializeString(prop.name) 24 | append(": ") 25 | serializePropertyValue(prop.get(obj)) 26 | } 27 | } 28 | 29 | private fun StringBuilder.serializeObject(obj: Any) { 30 | (obj::class as KClass) 31 | .memberProperties 32 | .filter { it.findAnnotation() == null } 33 | .joinToStringBuilder(this, prefix = "{", postfix = "}") { 34 | serializeProperty(it, obj) 35 | } 36 | } 37 | 38 | private fun StringBuilder.serializeProperty( 39 | prop: KProperty1, obj: Any 40 | ) { 41 | val jsonNameAnn = prop.findAnnotation() 42 | val propName = jsonNameAnn?.name ?: prop.name 43 | serializeString(propName) 44 | append(": ") 45 | 46 | val value = prop.get(obj) 47 | val jsonValue = prop.getSerializer()?.toJsonValue(value) ?: value 48 | serializePropertyValue(jsonValue) 49 | } 50 | 51 | fun KProperty<*>.getSerializer(): ValueSerializer? { 52 | val customSerializerAnn = findAnnotation() ?: return null 53 | val serializerClass = customSerializerAnn.serializerClass 54 | 55 | val valueSerializer = serializerClass.objectInstance 56 | ?: serializerClass.createInstance() 57 | @Suppress("UNCHECKED_CAST") 58 | return valueSerializer as ValueSerializer 59 | } 60 | 61 | private fun StringBuilder.serializePropertyValue(value: Any?) { 62 | when (value) { 63 | null -> append("null") 64 | is String -> serializeString(value) 65 | is Number, is Boolean -> append(value.toString()) 66 | is List<*> -> serializeList(value) 67 | else -> serializeObject(value) 68 | } 69 | } 70 | 71 | private fun StringBuilder.serializeList(data: List) { 72 | data.joinToStringBuilder(this, prefix = "[", postfix = "]") { 73 | serializePropertyValue(it) 74 | } 75 | } 76 | 77 | private fun StringBuilder.serializeString(s: String) { 78 | append('\"') 79 | s.forEach { append(it.escape()) } 80 | append('\"') 81 | } 82 | 83 | private fun Char.escape(): Any = 84 | when (this) { 85 | '\\' -> "\\\\" 86 | '\"' -> "\\\"" 87 | '\b' -> "\\b" 88 | '\u000C' -> "\\f" 89 | '\n' -> "\\n" 90 | '\r' -> "\\r" 91 | '\t' -> "\\t" 92 | else -> this 93 | } 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin in Action 2e: JKid Implementation [![JetBrains team project](https://jb.gg/badges/team-flat-square.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub) 2 | 3 | > **Note** 4 | > This project accompanies Chapter 12, "Introspecting Kotlin Code" of the [Kotlin in Action](https://kotl.in/in-action) 5 | > book. It is designed as an educational resource to illustrate concepts of working with annotations and reflections in 6 | > Kotlin. For production applications that require JSON serialization and deserialization, take a look 7 | > at [kotlinx.serialization](https://github.com/Kotlin/kotlinx.serialization). 8 | 9 | JKid is a case study of how to build a simple JSON serialization/deserialization library for Kotlin data classes. To 10 | serialize or deserialize an object use the `serialize` and `deserialize` functions. 11 | 12 | "Declaring and Applying Annotations" of chapter 12 describes annotations in Kotlin, and also shows how to use the 13 | library and how to tune it with annotations. 14 | You can find examples for this section in the folder `test/kotlin/examples`. 15 | Five examples correspond to five subsections accordingly. 16 | The file `kotlin/Annotations.kt` contains the declarations of discussed annotations. 17 | 18 | The section "Reflection: Introspecting Kotlin Objects at Runtime" of the book describes the implementation of serializer 19 | and deserializer. 20 | The files `main/kotlin/serialization/Serializer.kt` and `main/kotlin/deserialization/Deserializer.kt` contain the source 21 | code. 22 | 23 | ### Exercises 24 | 25 | We highly encourage you to do the following exercises after reading the text. Solving these exercises will help you to 26 | understand the concepts better and lets you practice right away. 27 | 28 | #### `DateFormat` support 29 | 30 | This first exercise can be started after reading the description of the serializer, specifically, after finishing the 31 | section "Customizing Serialization with Annotations." 32 | 33 | Support the annotation `DateFormat`, which allows you to annotate a date property with `@DateFormat("dd-MM-yyyy")`, 34 | specifying the date format as an argument. 35 | A unit test example that also illustrates its usage is in the file `test/kotlin/exercise/DateFormatAnnotation.kt`. 36 | Remove `@Ignore` from the test `DateFormatTest` and make the test pass. 37 | The declaration of the annotation is in the file `main/kotlin/exercise/DateFormat.kt`. 38 | The solution to this exercise can be found in the branch `solution-date-format`. 39 | 40 | #### Support for maps as property values 41 | 42 | The second exercise is intended to be started after reading the whole chapter. 43 | 44 | Currently, JKid only supports objects and collections as property values. 45 | Add support for the serialization and deserialization of maps as property values. 46 | You can find an unit test that serves as an example in `test/kotlin/exercise/Map.kt`. 47 | Remove `@Ignore` from the test `MapTest` and make it pass. 48 | 49 | To support deserialization of maps, create a class `MapSeed` similar to `ObjectSeed` and collection seeds. 50 | The function `createSeedForType` should now return an instance of `MapSeed` if a map is expected. 51 | The example solution can be found in the branch `solution-map`. 52 | -------------------------------------------------------------------------------- /src/test/kotlin/deserialization/ParserTest.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import kia.jkid.deserialization.ParserTest.JsonParserAction.* 4 | import java.io.StringReader 5 | import kotlin.test.Test 6 | import kotlin.test.assertEquals 7 | import kotlin.test.assertFailsWith 8 | 9 | class ParserTest { 10 | @Test fun testTrivial() { 11 | verifyParse("""{"s": "x"}""", VisitValue(0, "s", "x")) 12 | } 13 | 14 | @Test fun testTwoProperties() { 15 | verifyParse("""{"s": "x", "f": 1}""", 16 | VisitValue(0, "s", "x"), 17 | VisitValue(0, "f", 1L)) 18 | } 19 | 20 | @Test fun testMissingComma() { 21 | verifyMalformed("""{"s": "x" "f": 1}""") 22 | } 23 | 24 | @Test fun testNestedObject() { 25 | verifyParse("""{"s": {"x": 1}}""", 26 | CreateObject(1, "s"), 27 | VisitValue(1, "x", 1L)) 28 | } 29 | 30 | @Test fun testArray() { 31 | verifyParse("""{"s": [1, 2]}""", 32 | CreateArray(1, "s"), 33 | VisitValue(1, "s", 1L), 34 | VisitValue(1, "s", 2L)) 35 | } 36 | 37 | @Test fun testArrayOfObjects() { 38 | verifyParse("""{"s": [{"x": 1}, {"x": 2}]}""", 39 | CreateArray(1, "s"), 40 | CreateObject(2, "s"), 41 | VisitValue(2, "x", 1L), 42 | CreateObject(3, "s"), 43 | VisitValue(3, "x", 2L)) 44 | } 45 | 46 | private fun verifyParse(json: String, vararg expectedCallbackCalls: JsonParserAction) { 47 | val reportingObject = ReportingJsonObject(0) 48 | Parser(StringReader(json), reportingObject).parse() 49 | assertEquals(expectedCallbackCalls.size, reportingObject.actions.size) 50 | for ((expected, actual) in expectedCallbackCalls zip reportingObject.actions) { 51 | assertEquals(expected, actual) 52 | } 53 | } 54 | 55 | private fun verifyMalformed(text: String) { 56 | assertFailsWith { 57 | Parser(StringReader(text), ReportingJsonObject(0)).parse() 58 | } 59 | } 60 | 61 | interface JsonParserAction { 62 | data class CreateObject(val objId: Int, val propertyName: String) : JsonParserAction 63 | data class CreateArray(val objId: Int, val propertyName: String) : JsonParserAction 64 | data class VisitValue(val objId: Int, val propertyName: String, val value: Any?) : JsonParserAction 65 | } 66 | 67 | class ReportingData(var maxId: Int, val actions: MutableList = mutableListOf()) 68 | 69 | class ReportingJsonObject( 70 | val id: Int, 71 | private val reportingData: ReportingData = ReportingData(0, mutableListOf()) 72 | ) : JsonObject { 73 | val actions: List 74 | get() = reportingData.actions 75 | 76 | override fun setSimpleProperty(propertyName: String, value: Any?) { 77 | reportingData.actions.add(VisitValue(id, propertyName, value)) 78 | } 79 | 80 | override fun createObject(propertyName: String) = createCompositeProperty(propertyName, false) 81 | 82 | override fun createArray(propertyName: String) = createCompositeProperty(propertyName, true) 83 | 84 | private fun createCompositeProperty(propertyName: String, isCollection: Boolean): JsonObject { 85 | reportingData.maxId++ 86 | val newId = reportingData.maxId 87 | reportingData.actions.add(if (isCollection) CreateArray(newId, propertyName) else CreateObject(newId, propertyName)) 88 | return ReportingJsonObject(newId, reportingData) 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/deserialization/ClassInfoCache.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import kia.jkid.DeserializeInterface 4 | import kia.jkid.JsonName 5 | import kia.jkid.ValueSerializer 6 | import kia.jkid.serialization.getSerializer 7 | import kia.jkid.serializerForType 8 | import kotlin.reflect.KClass 9 | import kotlin.reflect.KParameter 10 | import kotlin.reflect.full.declaredMemberProperties 11 | import kotlin.reflect.full.findAnnotation 12 | import kotlin.reflect.full.primaryConstructor 13 | import kotlin.reflect.jvm.javaType 14 | 15 | class ClassInfoCache { 16 | private val cacheData = mutableMapOf, ClassInfo<*>>() 17 | 18 | @Suppress("UNCHECKED_CAST") 19 | operator fun get(cls: KClass): ClassInfo = 20 | cacheData.getOrPut(cls) { ClassInfo(cls) } as ClassInfo 21 | } 22 | 23 | class ClassInfo(cls: KClass) { 24 | private val className = cls.qualifiedName 25 | private val constructor = cls.primaryConstructor 26 | ?: throw JKidException("Class ${cls.qualifiedName} doesn't have a primary constructor") 27 | 28 | private val jsonNameToParamMap = hashMapOf() 29 | private val paramToSerializerMap = hashMapOf>() 30 | private val jsonNameToDeserializeClassMap = hashMapOf?>() 31 | 32 | init { 33 | constructor.parameters.forEach { cacheDataForParameter(cls, it) } 34 | } 35 | 36 | private fun cacheDataForParameter(cls: KClass<*>, param: KParameter) { 37 | val paramName = param.name 38 | ?: throw JKidException("Class $className has constructor parameter without name") 39 | 40 | val property = cls.declaredMemberProperties.find { it.name == paramName } ?: return 41 | val name = property.findAnnotation()?.name ?: paramName 42 | jsonNameToParamMap[name] = param 43 | 44 | val deserializeClass = property.findAnnotation()?.targetClass 45 | jsonNameToDeserializeClassMap[name] = deserializeClass 46 | 47 | val valueSerializer = property.getSerializer() 48 | ?: serializerForType(param.type) 49 | ?: return 50 | paramToSerializerMap[param] = valueSerializer 51 | } 52 | 53 | fun getConstructorParameter(propertyName: String): KParameter = jsonNameToParamMap[propertyName] 54 | ?: throw JKidException("Constructor parameter $propertyName is not found for class $className") 55 | 56 | fun getDeserializeClass(propertyName: String) = jsonNameToDeserializeClassMap[propertyName] 57 | 58 | fun deserializeConstructorArgument(param: KParameter, value: Any?): Any? { 59 | val serializer = paramToSerializerMap[param] 60 | if (serializer != null) return serializer.fromJsonValue(value) 61 | 62 | validateArgumentType(param, value) 63 | return value 64 | } 65 | 66 | private fun validateArgumentType(param: KParameter, value: Any?) { 67 | println("Validating $param with value $value") 68 | if (value == null && !param.type.isMarkedNullable) { 69 | throw JKidException("Received null value for non-null parameter ${param.name}") 70 | } 71 | if (value != null && value.javaClass != param.type.javaType) { 72 | throw JKidException("Type mismatch for parameter ${param.name}: " + 73 | "expected ${param.type.javaType}, found ${value.javaClass}") 74 | } 75 | } 76 | 77 | fun createInstance(arguments: Map): T { 78 | ensureAllParametersPresent(arguments) 79 | return constructor.callBy(arguments) 80 | } 81 | 82 | private fun ensureAllParametersPresent(arguments: Map) { 83 | for (param in constructor.parameters) { 84 | if (arguments[param] == null && !param.isOptional && !param.type.isMarkedNullable) { 85 | throw JKidException("Missing value for parameter ${param.name}") 86 | } 87 | } 88 | } 89 | } 90 | 91 | class JKidException(message: String) : Exception(message) 92 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/deserialization/Deserializer.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import kia.jkid.isPrimitiveOrString 4 | import kia.jkid.serializerForBasicType 5 | import java.io.Reader 6 | import java.io.StringReader 7 | import kotlin.reflect.KClass 8 | import kotlin.reflect.KParameter 9 | import kotlin.reflect.KType 10 | import kotlin.reflect.full.isSubtypeOf 11 | import kotlin.reflect.full.starProjectedType 12 | 13 | inline fun deserialize(json: String): T { 14 | return deserialize(StringReader(json)) 15 | } 16 | 17 | inline fun deserialize(json: Reader): T { 18 | return deserialize(json, T::class) 19 | } 20 | 21 | fun deserialize(json: Reader, targetClass: KClass): T { 22 | val seed = ObjectSeed(targetClass, ClassInfoCache()) 23 | Parser(json, seed).parse() 24 | return seed.spawn() 25 | } 26 | 27 | interface JsonObject { 28 | fun setSimpleProperty(propertyName: String, value: Any?) 29 | 30 | fun createObject(propertyName: String): JsonObject 31 | 32 | fun createArray(propertyName: String): JsonObject 33 | } 34 | 35 | interface Seed: JsonObject { 36 | val classInfoCache: ClassInfoCache 37 | 38 | fun spawn(): Any? 39 | 40 | fun createCompositeProperty(propertyName: String, isList: Boolean): JsonObject 41 | 42 | override fun createObject(propertyName: String) = createCompositeProperty(propertyName, false) 43 | 44 | override fun createArray(propertyName: String) = createCompositeProperty(propertyName, true) 45 | } 46 | 47 | private fun isSubtypeOfList(type: KType): Boolean { 48 | val listType: KType = List::class.starProjectedType 49 | return type.isSubtypeOf(listType) 50 | } 51 | 52 | private fun getParameterizedType(type: KType): KType { 53 | return type.arguments.single().type!! 54 | } 55 | 56 | fun Seed.createSeedForType(paramType: KType, isList: Boolean): Seed { 57 | val paramClass = paramType.classifier as KClass 58 | if (isSubtypeOfList(paramType)) { 59 | println("It's a list!") 60 | if (!isList) throw JKidException("An array expected, not a composite object") 61 | 62 | val elementType = getParameterizedType(paramType) 63 | if (elementType.isPrimitiveOrString()) { 64 | return ValueListSeed(elementType, classInfoCache) 65 | } 66 | return ObjectListSeed(elementType, classInfoCache) 67 | } 68 | if (isList) throw JKidException("Object of the type $paramType expected, not an array") 69 | return ObjectSeed(paramClass, classInfoCache) 70 | } 71 | 72 | 73 | class ObjectSeed( 74 | targetClass: KClass, 75 | override val classInfoCache: ClassInfoCache 76 | ) : Seed { 77 | 78 | private val classInfo: ClassInfo = classInfoCache[targetClass] 79 | 80 | private val valueArguments = mutableMapOf() 81 | private val seedArguments = mutableMapOf() 82 | 83 | private val arguments: Map 84 | get() = valueArguments + seedArguments.mapValues { it.value.spawn() } 85 | 86 | override fun setSimpleProperty(propertyName: String, value: Any?) { 87 | val param = classInfo.getConstructorParameter(propertyName) 88 | valueArguments[param] = classInfo.deserializeConstructorArgument(param, value) 89 | } 90 | 91 | override fun createCompositeProperty(propertyName: String, isList: Boolean): Seed { 92 | val param = classInfo.getConstructorParameter(propertyName) 93 | val deserializeAs = classInfo.getDeserializeClass(propertyName)?.starProjectedType 94 | val seed = createSeedForType( 95 | deserializeAs ?: param.type, isList 96 | ) 97 | return seed.apply { seedArguments[param] = this } 98 | } 99 | 100 | override fun spawn(): T = classInfo.createInstance(arguments) 101 | } 102 | 103 | class ObjectListSeed( 104 | val elementType: KType, 105 | override val classInfoCache: ClassInfoCache 106 | ) : Seed { 107 | private val elements = mutableListOf() 108 | 109 | override fun setSimpleProperty(propertyName: String, value: Any?) { 110 | throw JKidException("Found primitive value in collection of object types") 111 | } 112 | 113 | override fun createCompositeProperty(propertyName: String, isList: Boolean) = 114 | createSeedForType(elementType, isList).apply { elements.add(this) } 115 | 116 | override fun spawn(): List<*> = elements.map { it.spawn() } 117 | } 118 | 119 | class ValueListSeed( 120 | elementType: KType, 121 | override val classInfoCache: ClassInfoCache 122 | ) : Seed { 123 | private val elements = mutableListOf() 124 | private val serializerForType = serializerForBasicType(elementType) 125 | 126 | override fun setSimpleProperty(propertyName: String, value: Any?) { 127 | elements.add(serializerForType.fromJsonValue(value)) 128 | } 129 | 130 | override fun createCompositeProperty(propertyName: String, isList: Boolean): Seed { 131 | throw JKidException("Found object value in collection of primitive types") 132 | } 133 | 134 | override fun spawn() = elements 135 | } -------------------------------------------------------------------------------- /src/test/kotlin/deserialization/DeserializerTest.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import kia.jkid.* 4 | import java.util.* 5 | import kotlin.test.Test 6 | import kotlin.test.assertEquals 7 | import kotlin.test.assertFailsWith 8 | import kotlin.test.assertNull 9 | 10 | class DeserializerTest { 11 | @Test fun testSimple() { 12 | val result = deserialize("""{"s": "x"}""") 13 | assertEquals("x", result.s) 14 | } 15 | 16 | @Test fun testIntLong() { 17 | val result = deserialize("""{"i1": 42, "i2": 239}""") 18 | assertEquals(42, result.i1) 19 | assertEquals(239, result.i2) 20 | } 21 | 22 | @Test fun testTwoBools() { 23 | val result = deserialize("""{"b1": true, "b2": false}""") 24 | assertEquals(true, result.b1) 25 | assertEquals(false, result.b2) 26 | } 27 | 28 | @Test fun testNullableString() { 29 | val result = deserialize("""{"s": null}""") 30 | assertNull(result.s) 31 | } 32 | 33 | @Test fun testObject() { 34 | val result = deserialize("""{"o": {"s": "x"}}""") 35 | assertEquals("x", result.o.s) 36 | } 37 | 38 | @Test fun testList() { 39 | val result = deserialize("""{"o": ["a", "b"]}""") 40 | assertEquals(2, result.o.size) 41 | assertEquals("b", result.o[1]) 42 | } 43 | 44 | @Test fun testNullableList() { 45 | val result = deserialize("""{"o": [null, "b"]}""") 46 | assertEquals(2, result.o.size) 47 | assertEquals(null, result.o.first()) 48 | } 49 | 50 | @Test fun testObjectList() { 51 | val result = deserialize("""{"o": [{"s": "a"}, {"s": "b"}]}""") 52 | assertEquals(2, result.o.size) 53 | assertEquals("b", result.o[1].s) 54 | } 55 | 56 | @Test fun testOptionalArg() { 57 | val result = deserialize("{}") 58 | assertEquals("foo", result.s) 59 | } 60 | 61 | @Test fun testJsonName() { 62 | val result = deserialize("""{"q": "x"}""") 63 | assertEquals("x", result.s) 64 | } 65 | 66 | @Test fun testCustomDeserializer() { 67 | val result = deserialize("""{"x": "ONE"}""") 68 | assertEquals(1, result.x) 69 | } 70 | 71 | @Test fun testTimestampSerializer() { 72 | val result = deserialize("""{"x": 2000}""") 73 | assertEquals(2000, result.x.time) 74 | } 75 | 76 | @Test fun testJsonDeserialize() { 77 | val result = deserialize("""{"value": {"name": "Foo"}}""") 78 | assertEquals("Foo", result.value.name) 79 | } 80 | 81 | @Test fun testPropertyTypeMismatch() { 82 | assertFailsWith { 83 | deserialize("{\"s\": 1}") 84 | } 85 | } 86 | 87 | @Test fun testPropertyTypeMismatchNull() { 88 | assertFailsWith { 89 | deserialize("{\"s\": null}") 90 | } 91 | } 92 | 93 | @Test fun testMissingPropertyException() { 94 | assertFailsWith { 95 | deserialize("{}") 96 | } 97 | } 98 | 99 | @Test fun testListOfInts() { 100 | val result = deserialize("""{"ints": [42]}""") 101 | assertEquals(ListOfInts(listOf(42)), result) 102 | } 103 | 104 | @Test fun testObjectForListOfInts() { 105 | assertFailsWith { 106 | deserialize("""{"ints": {"a": 42}}""") 107 | } 108 | } 109 | } 110 | 111 | data class SingleStringProp(val s: String) 112 | 113 | data class SingleNullableStringProp(val s: String?) 114 | 115 | data class TwoIntProp(val i1: Int, val i2: Long) 116 | 117 | data class TwoBoolProp(val b1: Boolean, val b2: Boolean) 118 | 119 | data class SingleObjectProp(val o: SingleStringProp) 120 | 121 | data class SingleListProp(val o: List) 122 | 123 | data class SingleObjectListProp(val o: List) 124 | 125 | data class SingleOptionalProp(val s: String = "foo") 126 | 127 | data class ListOfInts(val ints: List) 128 | 129 | data class SingleAnnotatedStringProp(@JsonName("q") val s: String) 130 | 131 | data class TwoPropsOneExcluded(val s: String, @JsonExclude val x: String = "") 132 | 133 | class NumberSerializer: ValueSerializer { 134 | override fun fromJsonValue(jsonValue: Any?): Int = when(jsonValue) { 135 | "ZERO" -> 0 136 | "ONE" -> 1 137 | else -> throw JKidException("Unexpected value $jsonValue") 138 | } 139 | 140 | override fun toJsonValue(value: Int): Any = when (value) { 141 | 0 -> "ZERO" 142 | 1 -> "ONE" 143 | else -> "?" 144 | } 145 | } 146 | 147 | data class SingleCustomSerializedProp(@CustomSerializer(NumberSerializer::class) val x: Int) 148 | 149 | object TimestampSerializer : ValueSerializer { 150 | override fun toJsonValue(value: Date): Any = value.time 151 | 152 | override fun fromJsonValue(jsonValue: Any?): Date 153 | = Date((jsonValue as Number).toLong()) 154 | } 155 | 156 | data class SingleDateProp(@CustomSerializer(TimestampSerializer::class) val x: Date) 157 | 158 | interface ValueIntf { 159 | val name: String 160 | } 161 | 162 | data class ValueImpl(override val name: String) : ValueIntf 163 | 164 | data class ValueHolder(@DeserializeInterface(ValueImpl::class) val value: ValueIntf) 165 | -------------------------------------------------------------------------------- /src/main/kotlin/kia/jkid/deserialization/Lexer.kt: -------------------------------------------------------------------------------- 1 | package kia.jkid.deserialization 2 | 3 | import java.io.Reader 4 | 5 | interface Token { 6 | object COMMA : Token 7 | object COLON : Token 8 | object LBRACE : Token 9 | object RBRACE : Token 10 | object LBRACKET : Token 11 | object RBRACKET : Token 12 | 13 | interface ValueToken : Token { 14 | val value: Any? 15 | } 16 | 17 | object NullValue : ValueToken { 18 | override val value: Any? 19 | get() = null 20 | } 21 | 22 | data class BoolValue(override val value: Boolean) : ValueToken 23 | data class StringValue(override val value: String) : ValueToken 24 | data class LongValue(override val value: Long) : ValueToken 25 | data class DoubleValue(override val value: Double) : ValueToken 26 | 27 | companion object { 28 | val TRUE = BoolValue(true) 29 | val FALSE = BoolValue(false) 30 | } 31 | } 32 | 33 | class MalformedJSONException(message: String): Exception(message) 34 | 35 | internal class CharReader(val reader: Reader) { 36 | private val tokenBuffer = CharArray(4) 37 | private var nextChar: Char? = null 38 | var eof = false 39 | private set 40 | 41 | private fun advance() { 42 | if (eof) return 43 | val c = reader.read() 44 | if (c == -1) { 45 | eof = true 46 | } 47 | else { 48 | nextChar = c.toChar() 49 | } 50 | } 51 | 52 | fun peekNext(): Char? { 53 | if (nextChar == null) { 54 | advance() 55 | } 56 | return if (eof) null else nextChar 57 | } 58 | 59 | fun readNext() = peekNext().apply { nextChar = null } 60 | 61 | fun readNextChars(length: Int): String { 62 | assert(nextChar == null) 63 | assert(length <= tokenBuffer.size) 64 | if (reader.read(tokenBuffer, 0, length) != length) { 65 | throw MalformedJSONException("Premature end of data") 66 | } 67 | return String(tokenBuffer, 0, length) 68 | } 69 | 70 | fun expectText(text: String, followedBy: Set) { 71 | if (readNextChars(text.length) != text) { 72 | throw MalformedJSONException("Expected text $text") 73 | } 74 | val next = peekNext() 75 | if (next != null && next !in followedBy) 76 | throw MalformedJSONException("Expected text in $followedBy") 77 | } 78 | } 79 | 80 | class Lexer(reader: Reader) { 81 | private val charReader = CharReader(reader) 82 | 83 | companion object { 84 | private val valueEndChars = setOf(',', '}', ']', ' ', '\t', '\r', '\n') 85 | } 86 | 87 | private val tokenMap = hashMapOf Token> ( 88 | ',' to { c -> Token.COMMA }, 89 | '{' to { c -> Token.LBRACE }, 90 | '}' to { c -> Token.RBRACE }, 91 | '[' to { c -> Token.LBRACKET }, 92 | ']' to { c -> Token.RBRACKET }, 93 | ':' to { c -> Token.COLON }, 94 | 't' to { c -> charReader.expectText("rue", valueEndChars); Token.TRUE }, 95 | 'f' to { c -> charReader.expectText("alse", valueEndChars); Token.FALSE }, 96 | 'n' to { c -> charReader.expectText("ull", valueEndChars); Token.NullValue }, 97 | '"' to { c -> readStringToken() }, 98 | '-' to { c -> readNumberToken(c) } 99 | ).apply { 100 | for (i in '0'..'9') { 101 | this[i] = { c -> readNumberToken(c) } 102 | } 103 | } 104 | 105 | fun nextToken(): Token? { 106 | var c: Char? 107 | do { 108 | c = charReader.readNext() 109 | } while (c != null && c.isWhitespace()) 110 | if (c == null) return null 111 | 112 | return tokenMap[c]?.invoke(c) 113 | ?: throw MalformedJSONException("Unexpected token $c") 114 | } 115 | 116 | private fun readStringToken(): Token { 117 | val result = StringBuilder() 118 | while (true) { 119 | val c = charReader.readNext() ?: throw MalformedJSONException("Unterminated string") 120 | if (c == '"') break 121 | if (c == '\\') { 122 | val escaped = charReader.readNext() ?: throw MalformedJSONException("Unterminated escape sequence") 123 | when(escaped) { 124 | '\\', '/', '\"' -> result.append(escaped) 125 | 'b' -> result.append('\b') 126 | 'f' -> result.append('\u000C') 127 | 'n' -> result.append('\n') 128 | 'r' -> result.append('\r') 129 | 't' -> result.append('\t') 130 | 'u' -> { 131 | val hexChars = charReader.readNextChars(4) 132 | result.append(Integer.parseInt(hexChars, 16).toChar()) 133 | } 134 | else -> throw MalformedJSONException("Unsupported escape sequence \\$escaped") 135 | } 136 | } 137 | else { 138 | result.append(c) 139 | } 140 | } 141 | return Token.StringValue(result.toString()) 142 | } 143 | 144 | private fun readNumberToken(firstChar: Char): Token { 145 | val buffer = StringBuilder(firstChar.toString()) 146 | while (true) { 147 | val c = charReader.peekNext() 148 | if (c == null || c in valueEndChars) break 149 | buffer.append(charReader.readNext()!!) 150 | } 151 | val value = buffer.toString() 152 | return if (value.contains(".")) Token.DoubleValue(value.toDouble()) else Token.LongValue(value.toLong()) 153 | } 154 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | --------------------------------------------------------------------------------