Skip to content

Instantly share code, notes, and snippets.

@haohcraft
Created March 2, 2020 05:07
Show Gist options
  • Save haohcraft/9ab5a05e25ceb2207b605579ad945926 to your computer and use it in GitHub Desktop.
Save haohcraft/9ab5a05e25ceb2207b605579ad945926 to your computer and use it in GitHub Desktop.
object MyDateTypeAdapter : JsonDeserializer<Date>, JsonSerializer<Date> {
private val DATE_FORMATS = arrayOf("yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd")
private val dateFormatters: List<SimpleDateFormat> = DATE_FORMATS.map { SimpleDateFormat(it, Locale.US) }
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Date {
for (formatter in dateFormatters) {
try {
return formatter.parse(json?.asString)
} catch (ignore: ParseException) {
}
}
throw JsonParseException("DateParseException: " + json.toString())
}
override fun serialize(src: Date?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
synchronized(designatedFormat) {
val dateFormatAsString: String = designatedFormat.format(src)
return JsonPrimitive(dateFormatAsString)
}
}
}
val gson = GsonBuilder().apply {
registerTypeAdapter(Date::class.java, MyDateTypeAdapter)
}.create()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment