This commit is contained in:
InsanusMokrassar 2020-04-15 10:12:08 +06:00
parent fea8b243d7
commit 1afbfc0e04
9 changed files with 99 additions and 35 deletions

View File

@ -1,5 +1,14 @@
# SDI changelogs # SDI changelogs
## 0.3.0
* Versions:
* `Kotlin`: `1.3.70` -> `1.3.71`
* Common:
* Now it is possible to pass own lambda with receiver `SerializersModuleBuilder` to customize deserialization
* Now it will correctly resolve objects which was not previously registered
* By default, for modules loading will be used context from `Json`, passed as receiver
## 0.2.0 ## 0.2.0
* `Kotlin`: `1.3.61` -> `1.3.70` * `Kotlin`: `1.3.61` -> `1.3.70`

View File

@ -17,7 +17,7 @@ plugins {
id "org.jetbrains.kotlin.plugin.serialization" version "$kotlin_version" id "org.jetbrains.kotlin.plugin.serialization" version "$kotlin_version"
} }
project.version = "0.2.0" project.version = "0.3.0"
project.group = "com.insanusmokrassar" project.group = "com.insanusmokrassar"
apply from: "publish.gradle" apply from: "publish.gradle"

View File

@ -1,5 +1,5 @@
kotlin.code.style=official kotlin.code.style=official
kotlin_version=1.3.70 kotlin_version=1.3.71
kotlin_serialisation_runtime_version=0.20.0 kotlin_serialisation_runtime_version=0.20.0
gradle_bintray_plugin_version=1.8.4 gradle_bintray_plugin_version=1.8.4

View File

@ -2,16 +2,25 @@ package com.insanusmokrassar.sdi
import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.ImplicitReflectionSerializer
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModuleBuilder
internal val nonStrictJson = Json { internal val nonStrictJson = Json {
isLenient = true isLenient = true
ignoreUnknownKeys = true ignoreUnknownKeys = true
serializeSpecialFloatingPointValues = true serializeSpecialFloatingPointValues = true
useArrayPolymorphism = true
} }
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun Json.loadModule(json: String): Module = parse(ModuleDeserializerStrategy, json) private val ModuleDeserializerStrategyWithNullOptional = ModuleDeserializerStrategy()
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun loadModule(json: String): Module = nonStrictJson.loadModule(json) fun Json.loadModule(
json: String,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
): Module = parse(if (moduleBuilder != null) ModuleDeserializerStrategy(moduleBuilder) else ModuleDeserializerStrategyWithNullOptional, json)
@ImplicitReflectionSerializer
fun loadModule(
json: String,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
): Module = nonStrictJson.loadModule(json, moduleBuilder)

View File

@ -5,17 +5,19 @@ import kotlinx.serialization.*
import kotlinx.serialization.builtins.MapSerializer import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.* import kotlinx.serialization.json.*
import kotlinx.serialization.modules.SerializersModuleBuilder
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
internal object ModuleDeserializerStrategy : DeserializationStrategy<Module> { internal class ModuleDeserializerStrategy(
private val moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
) : DeserializationStrategy<Module> {
private val internalSerializer = MapSerializer(String.serializer(), ContextSerializer(Any::class)) private val internalSerializer = MapSerializer(String.serializer(), ContextSerializer(Any::class))
override val descriptor: SerialDescriptor override val descriptor: SerialDescriptor
get() = internalSerializer.descriptor get() = internalSerializer.descriptor
@InternalSerializationApi
override fun deserialize(decoder: Decoder): Module { override fun deserialize(decoder: Decoder): Module {
val json = JsonObjectSerializer.deserialize(decoder) val json = JsonObjectSerializer.deserialize(decoder)
val jsonSerialFormat = createModuleBasedOnConfigRoot(json) val jsonSerialFormat = createModuleBasedOnConfigRoot(json, moduleBuilder, decoder.context)
val resultJson = JsonObject( val resultJson = JsonObject(
json.keys.associateWith { JsonPrimitive(it) } json.keys.associateWith { JsonPrimitive(it) }
) )

View File

@ -2,11 +2,11 @@ package com.insanusmokrassar.sdi.utils
import kotlinx.serialization.* import kotlinx.serialization.*
import kotlinx.serialization.json.* import kotlinx.serialization.json.*
import kotlinx.serialization.modules.SerializerAlreadyRegisteredException
import kotlinx.serialization.modules.SerializersModuleBuilder import kotlinx.serialization.modules.SerializersModuleBuilder
import kotlin.reflect.KClass import kotlin.reflect.KClass
@InternalSerializationApi internal object AlreadyRegisteredException : Exception()
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
internal class DependencyResolver<T : Any>( internal class DependencyResolver<T : Any>(
serialModuleBuilder: SerializersModuleBuilder, serialModuleBuilder: SerializersModuleBuilder,
@ -17,19 +17,22 @@ internal class DependencyResolver<T : Any>(
private val originalSerializer: KSerializer<T> = try { private val originalSerializer: KSerializer<T> = try {
kClass.serializer() kClass.serializer()
} catch (e: Exception) { } catch (e: Exception) {
PolymorphicSerializer(kClass) ContextSerializer(kClass)
} }
private val objectsCache = mutableMapOf<String, T>() private val objectsCache = mutableMapOf<String, T>()
override val descriptor: SerialDescriptor = originalSerializer.descriptor override val descriptor: SerialDescriptor = originalSerializer.descriptor
init { init {
serialModuleBuilder.apply { serialModuleBuilder.apply {
contextual(kClass, this@DependencyResolver) try {
polymorphic(kClass, originalSerializer) contextual(kClass, this@DependencyResolver)
} catch (e: IllegalArgumentException) {
throw AlreadyRegisteredException
}
kClass.allSubclasses.forEach { currentKClass -> kClass.allSubclasses.forEach { currentKClass ->
try { try {
DependencyResolver(serialModuleBuilder, currentKClass, formatterGetter, dependencyGetter) DependencyResolver(serialModuleBuilder, currentKClass, formatterGetter, dependencyGetter)
} catch (e: SerializerAlreadyRegisteredException) { } catch (e: AlreadyRegisteredException) {
// ok // ok
} }
} }

View File

@ -3,8 +3,7 @@ package com.insanusmokrassar.sdi.utils
import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.ImplicitReflectionSerializer
import kotlinx.serialization.InternalSerializationApi import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.json.* import kotlinx.serialization.json.*
import kotlinx.serialization.modules.SerializerAlreadyRegisteredException import kotlinx.serialization.modules.*
import kotlinx.serialization.modules.SerializersModule
private typealias PackageOrOtherDependencyNamePair = Pair<String?, String?> private typealias PackageOrOtherDependencyNamePair = Pair<String?, String?>
@ -22,9 +21,12 @@ private fun JsonElement.resolvePackageName(currentKey: String, otherDependencies
} }
} }
@InternalSerializationApi
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
internal fun createModuleBasedOnConfigRoot(jsonObject: JsonObject): Json { internal fun createModuleBasedOnConfigRoot(
jsonObject: JsonObject,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null,
baseContext: SerialModule
): Json {
lateinit var caches: Map<String, () -> Any> lateinit var caches: Map<String, () -> Any>
lateinit var jsonStringFormat: Json lateinit var jsonStringFormat: Json
caches = jsonObject.keys.map { key -> caches = jsonObject.keys.map { key ->
@ -66,23 +68,28 @@ internal fun createModuleBasedOnConfigRoot(jsonObject: JsonObject): Json {
key to packageName key to packageName
}.toMap() }.toMap()
val context = SerializersModule { val context = baseContext.overwriteWith(
keysToPackages.values.forEach { SerializersModule {
val kclass = resolveKClassByPackageName(it) keysToPackages.values.forEach {
val kclass = resolveKClassByPackageName(it)
try { try {
DependencyResolver( DependencyResolver(
this, this,
kclass, kclass,
{ jsonStringFormat } { jsonStringFormat }
) { ) {
caches.getValue(it).invoke() caches.getValue(it).invoke()
}
} catch (e: AlreadyRegisteredException) {
// here we are thinking that already registered
} }
} catch (e: SerializerAlreadyRegisteredException) { }
// here we are thinking that already registered if (moduleBuilder != null) {
moduleBuilder()
} }
} }
} )
return Json( return Json(
configuration = JsonConfiguration(useArrayPolymorphism = true), configuration = JsonConfiguration(useArrayPolymorphism = true),
context = context context = context

View File

@ -31,8 +31,17 @@ class SimpleCustomObject_CustomController2(@ContextualSerialization val service:
println("Inited with name \"${service.names}\"") println("Inited with name \"${service.names}\"")
} }
} }
@Serializable
class SimpleCustomObject_CustomController3(@ContextualSerialization val service: SimpleCustomObject_ServiceAPI) : SimpleCustomObject_ControllerAPI {
override fun showUp() {
println("Inited with name \"${service.names}\"")
}
}
@Serializable @Serializable
class SimpleCustomObject_BusinessService(override val names: List<String>) : SimpleCustomObject_ServiceAPI class SimpleCustomObject_BusinessService(override val names: List<String>) : SimpleCustomObject_ServiceAPI
@Serializable
class SimpleCustomObject_BusinessService1(override val names: List<String>) : SimpleCustomObject_ServiceAPI
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
class SimpleCustomObjectTest { class SimpleCustomObjectTest {
@ -43,6 +52,7 @@ class SimpleCustomObjectTest {
val controllerName = "controller" val controllerName = "controller"
val customController1Name = "controller1" val customController1Name = "controller1"
val customController2Name = "controller2" val customController2Name = "controller2"
val customController3Name = "controller3"
val input = """ val input = """
{ {
"service": [ "service": [
@ -75,6 +85,17 @@ class SimpleCustomObjectTest {
"names": ${customNames.joinToString(prefix = "[", postfix = "]") { "\"$it\"" }} "names": ${customNames.joinToString(prefix = "[", postfix = "]") { "\"$it\"" }}
} }
} }
],
"$customController3Name": [
"${SimpleCustomObject_CustomController3::class.qualifiedName}",
{
"service": [
"${SimpleCustomObject_BusinessService1::class.qualifiedName}",
{
"names": ${customNames.joinToString(prefix = "[", postfix = "]") { "\"$it\"" }}
}
]
}
] ]
} }
""".trimIndent() """.trimIndent()

View File

@ -2,17 +2,30 @@ package com.insanusmokrassar.sdi
import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.ImplicitReflectionSerializer
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModuleBuilder
import java.io.File import java.io.File
import java.io.InputStream import java.io.InputStream
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun Json.loadModule(stream: InputStream) = loadModule(stream.reader().readText()) fun Json.loadModule(
stream: InputStream,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
) = loadModule(stream.reader().readText(), moduleBuilder)
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun loadModule(stream: InputStream) = nonStrictJson.loadModule(stream.reader().readText()) fun loadModule(
stream: InputStream,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
) = nonStrictJson.loadModule(stream, moduleBuilder)
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun Json.loadModule(file: File) = loadModule(file.inputStream()) fun Json.loadModule(
file: File,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
) = loadModule(file.inputStream(), moduleBuilder)
@ImplicitReflectionSerializer @ImplicitReflectionSerializer
fun loadModule(file: File) = nonStrictJson.loadModule(file.inputStream()) fun loadModule(
file: File,
moduleBuilder: (SerializersModuleBuilder.() -> Unit)? = null
) = nonStrictJson.loadModule(file, moduleBuilder)