@@ -19,6 +19,8 @@ import kotlin.test.assertEquals
19
19
import kotlinx.serialization.ExperimentalSerializationApi
20
20
import kotlinx.serialization.MissingFieldException
21
21
import kotlinx.serialization.SerializationException
22
+ import kotlinx.serialization.json.buildJsonObject
23
+ import kotlinx.serialization.json.put
22
24
import kotlinx.serialization.modules.SerializersModule
23
25
import kotlinx.serialization.modules.plus
24
26
import kotlinx.serialization.modules.polymorphic
@@ -71,6 +73,7 @@ import org.bson.codecs.kotlinx.samples.DataClassWithEncodeDefault
71
73
import org.bson.codecs.kotlinx.samples.DataClassWithEnum
72
74
import org.bson.codecs.kotlinx.samples.DataClassWithEnumMapKey
73
75
import org.bson.codecs.kotlinx.samples.DataClassWithFailingInit
76
+ import org.bson.codecs.kotlinx.samples.DataClassWithJsonElement
74
77
import org.bson.codecs.kotlinx.samples.DataClassWithMutableList
75
78
import org.bson.codecs.kotlinx.samples.DataClassWithMutableMap
76
79
import org.bson.codecs.kotlinx.samples.DataClassWithMutableSet
@@ -129,6 +132,46 @@ class KotlinSerializerCodecTest {
129
132
130
133
private val allBsonTypesDocument = BsonDocument .parse(allBsonTypesJson)
131
134
135
+ @Test
136
+ fun testDataClassWithJsonElement () {
137
+
138
+ /*
139
+ * We need to encode all integer values as longs because the JsonElementSerializer
140
+ * doesn't actually use our JsonEncoder instead it uses an inferior
141
+ * JsonPrimitiveSerializer and ignores ours altogether encoding all integers as longs
142
+ *
143
+ * On the other hand, BsonDocument decodes everything as integers unless it's explicitly
144
+ * set as a long, and therefore we get a type mismatch
145
+ */
146
+
147
+ val expected = """ {"value": {
148
+ |"char": "c",
149
+ |"byte": {"$numberLong ": "0"},
150
+ |"short": {"$numberLong ": "1"},
151
+ |"int": {"$numberLong ": "22"},
152
+ |"long": {"$numberLong ": "42"},
153
+ |"float": 4.0,
154
+ |"double": 4.2,
155
+ |"boolean": true,
156
+ |"string": "String"
157
+ |}}""" .trimMargin()
158
+ val dataClass = DataClassWithJsonElement (
159
+ buildJsonObject {
160
+ put(" char" , " c" )
161
+ put(" byte" , 0 )
162
+ put(" short" , 1 )
163
+ put(" int" , 22 )
164
+ put(" long" , 42L )
165
+ put(" float" , 4.0 )
166
+ put(" double" , 4.2 )
167
+ put(" boolean" , true )
168
+ put(" string" , " String" )
169
+ }
170
+ )
171
+
172
+ assertRoundTrips(expected, dataClass)
173
+ }
174
+
132
175
@Test
133
176
fun testDataClassWithSimpleValues () {
134
177
val expected =
0 commit comments