Created
June 6, 2019 12:46
-
-
Save gotev/4422b2da532b28647b0ac9b6ab8fef8a to your computer and use it in GitHub Desktop.
ISO8601 Gson Type Adapters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.GsonBuilder | |
import com.google.gson.TypeAdapter | |
import com.google.gson.stream.JsonReader | |
import com.google.gson.stream.JsonWriter | |
import org.threeten.bp.* | |
private fun LocalDateTime.toISO8601UTCString() = withNano(0).atOffset(ZoneOffset.UTC).toString() | |
abstract class NullableTypeAdapter<T> : TypeAdapter<T>() { | |
override fun write(writer: JsonWriter?, value: T) { | |
if (value == null) { | |
writer?.nullValue() | |
} else { | |
writer?.value(valueToString(value)) | |
} | |
} | |
override fun read(reader: JsonReader?): T? { | |
return if (reader?.peek() == null) { | |
reader?.nextNull() | |
null | |
} else { | |
stringToValue(reader.nextString()) | |
} | |
} | |
abstract fun valueToString(value: T): String | |
abstract fun stringToValue(string: String): T | |
} | |
class Iso8601LocalDateTimeTypeAdapter : NullableTypeAdapter<LocalDateTime>() { | |
override fun valueToString(value: LocalDateTime) = value.toISO8601UTCString() | |
override fun stringToValue(string: String) = Instant.parse(string).atZone(ZoneId.systemDefault()).toLocalDateTime() | |
} | |
class Iso8601LocalDateTypeAdapter : NullableTypeAdapter<LocalDate>() { | |
override fun valueToString(value: LocalDate) = value.toString() | |
override fun stringToValue(string: String) = LocalDate.parse(string) | |
} | |
fun GsonBuilder.registerISO8601TypeAdapters() = | |
registerTypeAdapter(LocalDateTime::class.java, Iso8601LocalDateTimeTypeAdapter()) | |
.registerTypeAdapter(LocalDate::class.java, Iso8601LocalDateTypeAdapter()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment