blob: ee373e7a0ccae30513187b5d138f920c4ae76685 (
plain)
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
|
package kotlinx.serialization.features
import kotlinx.serialization.*
import kotlinx.serialization.internal.IntDescriptor
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
object MultiplyingIntSerializer : KSerializer<Int> {
override val descriptor: SerialDescriptor
get() = IntDescriptor
override fun deserialize(decoder: Decoder): Int {
return decoder.decodeInt() / 2
}
override fun serialize(encoder: Encoder, obj: Int) {
encoder.encodeInt(obj * 2)
}
}
object DividingIntSerializer : KSerializer<Int> {
override val descriptor: SerialDescriptor
get() = IntDescriptor
override fun deserialize(decoder: Decoder): Int {
return decoder.decodeInt() * 2
}
override fun serialize(encoder: Encoder, obj: Int) {
encoder.encodeInt(obj / 2)
}
}
@Serializable(with = DividingIntHolderSerializer::class)
data class IntHolder(val data: Int)
@Serializer(IntHolder::class)
object MultiplyingIntHolderSerializer {
override fun deserialize(decoder: Decoder): IntHolder {
return IntHolder(decoder.decodeInt() / 2)
}
override fun serialize(encoder: Encoder, obj: IntHolder) {
encoder.encodeInt(obj.data * 2)
}
}
@Serializer(IntHolder::class)
object DividingIntHolderSerializer {
override fun deserialize(decoder: Decoder): IntHolder {
return IntHolder(decoder.decodeInt() * 2)
}
override fun serialize(encoder: Encoder, obj: IntHolder) {
encoder.encodeInt(obj.data / 2)
}
}
@Serializable
data class Carrier(
@Serializable(with = MultiplyingIntHolderSerializer::class) val a: IntHolder,
@Serializable(with = MultiplyingIntSerializer::class) val i: Int
)
class SerializableWithTest {
@Test
fun testOnProperties() {
val str = Json.stringify(Carrier.serializer(), Carrier(IntHolder(42), 2))
assertEquals("""{"a":84,"i":4}""", str)
}
}
|