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
|
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.internal.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.collections.set
import kotlin.jvm.*
internal fun <T> Json.writeJson(value: T, serializer: SerializationStrategy<T>): JsonElement {
lateinit var result: JsonElement
val encoder = JsonTreeEncoder(this) { result = it }
encoder.encode(serializer, value)
return result
}
private sealed class AbstractJsonTreeEncoder(
final override val json: Json,
val nodeConsumer: (JsonElement) -> Unit
) : NamedValueEncoder(), JsonEncoder {
final override val context: SerialModule
get() = json.context
@JvmField
protected val configuration = json.configuration
private var writePolymorphic = false
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
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.serializeSpecialFloatingPointValues && !value.isFinite()) {
throw InvalidFloatingPoint(value, tag, "float", 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.kind !is PrimitiveKind && serializer.descriptor.kind !== UnionKind.ENUM_KIND) {
encodePolymorphically(serializer, value) { writePolymorphic = true }
} else JsonPrimitiveEncoder(json, nodeConsumer).apply {
encodeSerializableValue(serializer, value)
endEncode(serializer.descriptor)
}
}
override fun encodeTaggedDouble(tag: String, value: Double) {
// First encode value, then check, to have a prettier error message
putElement(tag, JsonPrimitive(value))
if (!configuration.serializeSpecialFloatingPointValues && !value.isFinite()) {
throw InvalidFloatingPoint(value, tag, "double", 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,
enumDescription: SerialDescriptor,
ordinal: Int
) = putElement(tag, JsonPrimitive(enumDescription.getElementName(ordinal)))
override fun encodeTaggedValue(tag: String, value: Any) {
putElement(tag, JsonPrimitive(value.toString()))
}
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)
}
if (writePolymorphic) {
writePolymorphic = false
encoder.putElement(configuration.classDiscriminator, JsonPrimitive(descriptor.serialName))
}
return encoder
}
override fun endEncode(descriptor: SerialDescriptor) {
nodeConsumer(getCurrent())
}
}
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
}
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 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)
}
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
}
|