Created
April 14, 2020 10:55
-
-
Save pkozlovskiy/fbfd87a4a7528b27f55ba34edb157188 to your computer and use it in GitHub Desktop.
This file contains 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.* | |
import org.threeten.bp.LocalDateTime | |
import org.threeten.bp.OffsetDateTime | |
import org.threeten.bp.ZoneOffset | |
import org.threeten.bp.format.DateTimeFormatter | |
import org.threeten.bp.format.DateTimeFormatterBuilder | |
import org.threeten.bp.temporal.ChronoField | |
import java.lang.reflect.Type | |
/** | |
* TypeAdapter используемый для конвертации строк с датой в объекты типа OffsetDateTime | |
*/ | |
class OffsetDateTimeTypeAdapter : JsonSerializer<OffsetDateTime>, JsonDeserializer<OffsetDateTime> { | |
override fun serialize(src: OffsetDateTime, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { | |
return JsonPrimitive(DateTimeFormatter.ISO_DATE_TIME.format(src)) | |
} | |
@Throws(JsonParseException::class) | |
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): OffsetDateTime { | |
return LocalDateTime.parse(json.asString, FORMATTER).atOffset(ZoneOffset.UTC) | |
} | |
companion object { | |
private const val DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss" | |
private val FORMATTER = DateTimeFormatterBuilder() | |
.parseCaseInsensitive() | |
.appendPattern(DATE_TIME_FORMAT_PATTERN) | |
.optionalStart() | |
.appendFraction(ChronoField.MICRO_OF_SECOND, 1, 7, true) | |
.optionalEnd() | |
.optionalStart() | |
.appendZoneId() | |
.optionalEnd() | |
.optionalStart() | |
.appendPattern("Z") | |
.optionalEnd() | |
.toFormatter() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment