-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonViewModelPolymorphicSerializer.kt
More file actions
83 lines (70 loc) · 3.51 KB
/
JsonViewModelPolymorphicSerializer.kt
File metadata and controls
83 lines (70 loc) · 3.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.dmm.eikaiwa.viewmodels
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.modules.SerializersModule
import kotlin.reflect.KClass
// This implementation is copied from kotlinx.serialization.json.JsonContentPolymorphicSerializer.
// Access to the encoder/decoder is needed in order to retrieve the reference cache, and the
// implementation didn't allow it.
abstract class JsonViewModelPolymorphicSerializer<T : Any>(
private val baseClass: KClass<T>
) : KSerializer<T> {
override val descriptor: SerialDescriptor =
buildClassSerialDescriptor("JsonContentPolymorphicSerializer<${baseClass.simpleName}>")
private fun referenceCache(serializersModule: SerializersModule): ViewModelReferenceCache =
(serializersModule.getContextual(ViewModelContext::class) as ViewModelContextSerializer).referenceCache
protected abstract fun deserializerForType(type: String): DeserializationStrategy<T>
final override fun serialize(encoder: Encoder, value: T) {
TODO()
}
final override fun deserialize(decoder: Decoder): T {
require(decoder is JsonDecoder)
val tree = decoder.decodeJsonElement()
val actualSerializer = selectDeserializer(tree, decoder) as KSerializer<T>
return decoder.json.decodeFromJsonElement(actualSerializer, tree)
}
/**
* Determines a particular strategy for deserialization by looking on a parsed JSON [element].
*/
private fun selectDeserializer(element: JsonElement, decoder: Decoder): DeserializationStrategy<T> {
val referenceCache = referenceCache(decoder.serializersModule)
// Normally, it would be enough just inspecting the type, but we need to deal with references.
return when {
// If a reference.
"_ref" in element.jsonObject -> {
// Parse key.
val key = element.jsonObject["_ref"]!!.jsonPrimitive.content
// Check for cached object.
val cachedObject = referenceCache.raw[key]
?: throw ReferenceNotFoundException(key, referenceCache)
// Check for type.
val type = getType(cachedObject)
// Return deserializer for type.
deserializerForType(type)
}
else -> {
val type = getType(element)
deserializerForType(type)
}
}
}
private fun getType(element: JsonElement): String =
element.jsonObject["_type"]?.jsonPrimitive?.content
?: throw MissingTypeException(baseClass)
private fun throwSubtypeNotRegistered(subClass: KClass<*>, baseClass: KClass<*>): Nothing {
val subClassName = subClass.simpleName ?: "$subClass"
val scope = "in the scope of '${baseClass.simpleName}'"
throw SerializationException(
"Class '${subClassName}' is not registered for polymorphic serialization $scope.\n" +
"Mark the base class as 'sealed' or register the serializer explicitly.")
}
}