46 lines
1.7 KiB
Kotlin
46 lines
1.7 KiB
Kotlin
package com.bitcointxoko.gudariwallet.api
|
|
|
|
import kotlinx.serialization.ExperimentalSerializationApi
|
|
import kotlinx.serialization.KSerializer
|
|
import kotlinx.serialization.descriptors.SerialDescriptor
|
|
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
|
|
import kotlinx.serialization.encoding.Decoder
|
|
import kotlinx.serialization.encoding.Encoder
|
|
import kotlinx.serialization.json.JsonArray
|
|
import kotlinx.serialization.json.JsonDecoder
|
|
import kotlinx.serialization.json.JsonNull
|
|
import kotlinx.serialization.json.JsonPrimitive
|
|
import kotlinx.serialization.json.jsonPrimitive
|
|
|
|
/**
|
|
* LNbits returns `comment` in PaymentExtra as either:
|
|
* - a plain string "Thanks!"
|
|
* - a JSON array ["Thanks!"]
|
|
* - null
|
|
*
|
|
* Mirrors the behavior of the old Gson FlexibleStringAdapter.
|
|
*/
|
|
object FlexibleStringSerializer : KSerializer<String?> {
|
|
|
|
override val descriptor: SerialDescriptor =
|
|
buildClassSerialDescriptor("FlexibleString")
|
|
|
|
@OptIn(ExperimentalSerializationApi::class)
|
|
override fun serialize(encoder: Encoder, value: String?) {
|
|
if (value == null) encoder.encodeNull()
|
|
else encoder.encodeString(value)
|
|
}
|
|
|
|
override fun deserialize(decoder: Decoder): String? {
|
|
val jsonDecoder = decoder as JsonDecoder
|
|
return when (val element = jsonDecoder.decodeJsonElement()) {
|
|
is JsonNull -> null
|
|
is JsonPrimitive -> element.content // plain string → as-is
|
|
is JsonArray -> element // array → join elements
|
|
.mapNotNull { if (it is JsonNull) null else it.jsonPrimitive.content }
|
|
.joinToString(", ")
|
|
.ifEmpty { null }
|
|
else -> null
|
|
}
|
|
}
|
|
} |