/
TreeJsonEncoder.kt
266 lines (217 loc) · 10.6 KB
/
TreeJsonEncoder.kt
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalSerializationApi::class)
package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.internal.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.collections.set
import kotlin.jvm.*
@JsonFriendModuleApi
public fun <T> writeJson(json: Json, value: T, serializer: SerializationStrategy<T>): JsonElement {
lateinit var result: JsonElement
val encoder = JsonTreeEncoder(json) { result = it }
encoder.encodeSerializableValue(serializer, value)
return result
}
@ExperimentalSerializationApi
private sealed class AbstractJsonTreeEncoder(
final override val json: Json,
protected val nodeConsumer: (JsonElement) -> Unit
) : NamedValueEncoder(), JsonEncoder {
final override val serializersModule: SerializersModule
get() = json.serializersModule
@JvmField
protected val configuration = json.configuration
private var polymorphicDiscriminator: String? = null
private var polymorphicSerialName: String? = null
override fun elementName(descriptor: SerialDescriptor, index: Int): String =
descriptor.getJsonElementName(json, index)
override fun encodeJsonElement(element: JsonElement) {
encodeSerializableValue(JsonElementSerializer, element)
}
override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean =
configuration.encodeDefaults
override fun composeName(parentName: String, childName: String): String = childName
abstract fun putElement(key: String, element: JsonElement)
abstract fun getCurrent(): JsonElement
// has no tag when encoding a nullable element at root level
override fun encodeNotNullMark() {}
// has no tag when encoding a nullable element at root level
override fun encodeNull() {
val tag = currentTagOrNull ?: return nodeConsumer(JsonNull)
encodeTaggedNull(tag)
}
override fun encodeTaggedNull(tag: String) = putElement(tag, JsonNull)
override fun encodeTaggedInt(tag: String, value: Int) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedByte(tag: String, value: Byte) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedShort(tag: String, value: Short) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedLong(tag: String, value: Long) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedFloat(tag: String, value: Float) {
// First encode value, then check, to have a prettier error message
putElement(tag, JsonPrimitive(value))
if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) {
throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString())
}
}
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
// Writing non-structured data (i.e. primitives) on top-level (e.g. without any tag) requires special output
if (currentTagOrNull != null || !serializer.descriptor.carrierDescriptor(serializersModule).requiresTopLevelTag) {
encodePolymorphically(serializer, value) { polymorphicDiscriminator = it }
} else JsonPrimitiveEncoder(json, nodeConsumer).apply {
encodeSerializableValue(serializer, value)
}
}
override fun encodeTaggedDouble(tag: String, value: Double) {
// First encode value, then check, to have a prettier error message
putElement(tag, JsonPrimitive(value))
if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) {
throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString())
}
}
override fun encodeTaggedBoolean(tag: String, value: Boolean) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedChar(tag: String, value: Char) = putElement(tag, JsonPrimitive(value.toString()))
override fun encodeTaggedString(tag: String, value: String) = putElement(tag, JsonPrimitive(value))
override fun encodeTaggedEnum(
tag: String,
enumDescriptor: SerialDescriptor,
ordinal: Int
) = putElement(tag, JsonPrimitive(enumDescriptor.getElementName(ordinal)))
override fun encodeTaggedValue(tag: String, value: Any) {
putElement(tag, JsonPrimitive(value.toString()))
}
override fun encodeTaggedInline(tag: String, inlineDescriptor: SerialDescriptor): Encoder =
when {
inlineDescriptor.isUnsignedNumber -> inlineUnsignedNumberEncoder(tag)
inlineDescriptor.isUnquotedLiteral -> inlineUnquotedLiteralEncoder(tag, inlineDescriptor)
else -> super.encodeTaggedInline(tag, inlineDescriptor)
}
override fun encodeInline(descriptor: SerialDescriptor): Encoder {
return if (currentTagOrNull != null) {
if (polymorphicDiscriminator != null) polymorphicSerialName = descriptor.serialName
super.encodeInline(descriptor)
} else {
JsonPrimitiveEncoder(json, nodeConsumer).encodeInline(descriptor)
}
}
@SuppressAnimalSniffer // Long(Integer).toUnsignedString(long)
private fun inlineUnsignedNumberEncoder(tag: String) = object : AbstractEncoder() {
override val serializersModule: SerializersModule = json.serializersModule
fun putUnquotedString(s: String) = putElement(tag, JsonLiteral(s, isString = false))
override fun encodeInt(value: Int) = putUnquotedString(value.toUInt().toString())
override fun encodeLong(value: Long) = putUnquotedString(value.toULong().toString())
override fun encodeByte(value: Byte) = putUnquotedString(value.toUByte().toString())
override fun encodeShort(value: Short) = putUnquotedString(value.toUShort().toString())
}
private fun inlineUnquotedLiteralEncoder(tag: String, inlineDescriptor: SerialDescriptor) = object : AbstractEncoder() {
override val serializersModule: SerializersModule get() = json.serializersModule
override fun encodeString(value: String) = putElement(tag, JsonLiteral(value, isString = false, coerceToInlineType = inlineDescriptor))
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
val consumer =
if (currentTagOrNull == null) nodeConsumer
else { node -> putElement(currentTag, node) }
val encoder = when (descriptor.kind) {
StructureKind.LIST, is PolymorphicKind -> JsonTreeListEncoder(json, consumer)
StructureKind.MAP -> json.selectMapMode(
descriptor,
{ JsonTreeMapEncoder(json, consumer) },
{ JsonTreeListEncoder(json, consumer) }
)
else -> JsonTreeEncoder(json, consumer)
}
val discriminator = polymorphicDiscriminator
if (discriminator != null) {
encoder.putElement(discriminator, JsonPrimitive(polymorphicSerialName ?: descriptor.serialName))
polymorphicDiscriminator = null
polymorphicSerialName = null
}
return encoder
}
override fun endEncode(descriptor: SerialDescriptor) {
nodeConsumer(getCurrent())
}
}
private val SerialDescriptor.requiresTopLevelTag: Boolean
get() = kind is PrimitiveKind || kind === SerialKind.ENUM
internal const val PRIMITIVE_TAG = "primitive" // also used in JsonPrimitiveInput
private class JsonPrimitiveEncoder(
json: Json,
nodeConsumer: (JsonElement) -> Unit
) : AbstractJsonTreeEncoder(json, nodeConsumer) {
private var content: JsonElement? = null
init {
pushTag(PRIMITIVE_TAG)
}
override fun putElement(key: String, element: JsonElement) {
require(key === PRIMITIVE_TAG) { "This output can only consume primitives with '$PRIMITIVE_TAG' tag" }
require(content == null) { "Primitive element was already recorded. Does call to .encodeXxx happen more than once?" }
content = element
nodeConsumer(element)
}
override fun getCurrent(): JsonElement =
requireNotNull(content) { "Primitive element has not been recorded. Is call to .encodeXxx is missing in serializer?" }
}
private open class JsonTreeEncoder(
json: Json, nodeConsumer: (JsonElement) -> Unit
) : AbstractJsonTreeEncoder(json, nodeConsumer) {
protected val content: MutableMap<String, JsonElement> = linkedMapOf()
override fun putElement(key: String, element: JsonElement) {
content[key] = element
}
override fun <T : Any> encodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
serializer: SerializationStrategy<T>,
value: T?
) {
if (value != null || configuration.explicitNulls) {
super.encodeNullableSerializableElement(descriptor, index, serializer, value)
}
}
override fun getCurrent(): JsonElement = JsonObject(content)
}
private class JsonTreeMapEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) : JsonTreeEncoder(json, nodeConsumer) {
private lateinit var tag: String
private var isKey = true
override fun putElement(key: String, element: JsonElement) {
if (isKey) { // writing key
tag = when (element) {
is JsonPrimitive -> element.content
is JsonObject -> throw InvalidKeyKindException(JsonObjectSerializer.descriptor)
is JsonArray -> throw InvalidKeyKindException(JsonArraySerializer.descriptor)
}
isKey = false
} else {
content[tag] = element
isKey = true
}
}
override fun getCurrent(): JsonElement {
return JsonObject(content)
}
}
private class JsonTreeListEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) :
AbstractJsonTreeEncoder(json, nodeConsumer) {
private val array: ArrayList<JsonElement> = arrayListOf()
override fun elementName(descriptor: SerialDescriptor, index: Int): String = index.toString()
override fun putElement(key: String, element: JsonElement) {
val idx = key.toInt()
array.add(idx, element)
}
override fun getCurrent(): JsonElement = JsonArray(array)
}
@OptIn(ExperimentalSerializationApi::class)
internal inline fun <reified T : JsonElement> cast(value: JsonElement, descriptor: SerialDescriptor): T {
if (value !is T) {
throw JsonDecodingException(
-1,
"Expected ${T::class} as the serialized body of ${descriptor.serialName}, but had ${value::class}"
)
}
return value
}