Created
March 2, 2020 05:07
-
-
Save haohcraft/9ab5a05e25ceb2207b605579ad945926 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
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