All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin-client.jvm-common.infrastructure.LocalDateAdapter.kt.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
package {{packageName}}.infrastructure

{{#moshi}}
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
{{/moshi}}
{{#gson}}
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
{{/gson}}
{{#kotlinx_serialization}}
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.SerialDescriptor
{{/kotlinx_serialization}}
{{^threetenbp}}
import java.time.LocalDate
import java.time.format.DateTimeFormatter
{{/threetenbp}}
{{#threetenbp}}
import org.threeten.bp.LocalDate
import org.threeten.bp.format.DateTimeFormatter
{{/threetenbp}}

{{#moshi}}
{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter {
    @ToJson
    fun toJson(value: LocalDate): String {
        return DateTimeFormatter.ISO_LOCAL_DATE.format(value)
    }

    @FromJson
    fun fromJson(value: String): LocalDate {
        return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE)
    }

}
{{/moshi}}
{{#gson}}
{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter() {
    @Throws(IOException::class)
    override fun write(out: JsonWriter?, value: LocalDate?) {
        if (value == null) {
            out?.nullValue()
        } else {
            out?.value(formatter.format(value))
        }
    }

    @Throws(IOException::class)
    override fun read(out: JsonReader?): LocalDate? {
        out ?: return null

        when (out.peek()) {
            NULL -> {
                out.nextNull()
                return null
            }
            else -> {
                return LocalDate.parse(out.nextString(), formatter)
            }
        }
    }
}
{{/gson}}
{{#kotlinx_serialization}}
@Serializer(forClass = LocalDate::class)
{{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateAdapter : KSerializer {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: LocalDate) {
        encoder.encodeString(DateTimeFormatter.ISO_LOCAL_DATE.format(value))
    }

    override fun deserialize(decoder: Decoder): LocalDate {
        return LocalDate.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE)
    }
}
{{/kotlinx_serialization}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy