-
Notifications
You must be signed in to change notification settings - Fork 6
/
0030-TypeEncoderCodecs.kt
47 lines (35 loc) · 1.25 KB
/
0030-TypeEncoderCodecs.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
package examples
import com.github.fluidsonic.fluid.json.*
import java.time.Instant
object EncodingExample {
@JvmStatic
fun main(args: Array<String>) {
// Using a codec for encoding specific Kotlin types simplifies JSON serialization a lot
val serializer = JSONSerializer.builder()
.encodingWith(EventCodec)
.build()
val json = serializer.serializeValue(listOf(
Event(id = 1, date = Instant.ofEpochSecond(1000000000), title = "One"),
Event(id = 2, date = Instant.ofEpochSecond(2000000000), title = "Two"),
Event(id = 3, date = Instant.ofEpochSecond(3000000000), title = "Three"),
Event(id = 4, date = Instant.ofEpochSecond(4000000000), title = "Four"),
Event(id = 5, date = Instant.ofEpochSecond(5000000000), title = "Five"),
Event(id = 6, title = "Six")
))
println(json)
}
private data class Event(
val id: Int,
val date: Instant? = null,
val title: String
)
private object EventCodec : AbstractJSONEncoderCodec<Event, JSONCoderContext>() {
override fun encode(value: Event, encoder: JSONEncoder<JSONCoderContext>) {
encoder.writeIntoMap {
writeMapElement("id", int = value.id)
writeMapElement("date", value = value.date, skipIfNull = true)
writeMapElement("title", string = value.title)
}
}
}
}