Serialize OffsetDateTime

Signed-off-by: Etzelia <etzelia@hotmail.com>
kotlin
Etzelia 2021-06-20 15:21:23 -05:00
parent abf36d1eb2
commit 41dbde93d9
No known key found for this signature in database
GPG Key ID: 708511AE7ABC5314
2 changed files with 26 additions and 8 deletions

View File

@ -1,19 +1,25 @@
package xyz.etztech.javacord.embed
import java.time.OffsetDateTime
import kotlinx.serialization.Contextual
import java.time.format.DateTimeFormatter
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encodeToString
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
@Serializable
class Embed {
private var content = ""
private var title = ""
private var description = ""
private var url = ""
private var color = 0
@Contextual
private var content: String? = null
private var title: String? = null
private var description: String? = null
private var url: String? = null
private var color: Int? = null
@Serializable(with = OffsetDateTimeSerializer::class)
private var timestamp: OffsetDateTime? = null
private var footer: Footer? = null
private var thumbnail: Thumbnail? = null
@ -83,4 +89,13 @@ class Embed {
override fun toString(): String {
return Json.encodeToString(this)
}
}
object OffsetDateTimeSerializer : KSerializer<OffsetDateTime> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("OffsetDateTime", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: OffsetDateTime) =
encoder.encodeString(value.format(DateTimeFormatter.ISO_INSTANT))
override fun deserialize(decoder: Decoder): OffsetDateTime =
OffsetDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_INSTANT)
}

View File

@ -1,5 +1,6 @@
package xyz.etztech.javacord.embed
import java.time.OffsetDateTime
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
@ -18,9 +19,11 @@ class EmbedTest {
Field("Field3", "baz", true)
)
)
.timestamp(OffsetDateTime.MIN)
val expected =
"{\"title\":\"Test \\\"Title\\\"\",\"description\":\"Test Description\",\"color\"" +
":1381653,\"author\":{\"name\":\"Etzelia\",\"url\":\"https://etzel.ia\",\"iconURL" +
":1381653,\"timestamp\":\"-1000000000-12-31T06:00:00Z\",\"author\":{\"name\":\"" +
"Etzelia\",\"url\":\"https://etzel.ia\",\"iconURL" +
"\":\"\",\"proxyIconURL\":\"\"},\"fields\":[{\"name\":\"Field1\",\"value\":\"foo" +
"\",\"inline\":false},{\"name\":\"Field2\",\"value\":\"bar\",\"inline\":false},{" +
"\"name\":\"Field3\",\"value\":\"baz\",\"inline\":true}]}"