【发布时间】:2018-12-16 19:44:39
【问题描述】:
我会以 ISO8601 格式发送我所有的带有改造的日期。 我只是这样做:
private fun createGsonInstance(): Gson {
return GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
.create()
}
private fun createRetrofitInstance(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
debug { SessionManager.Pref.serverUrl }
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(SessionManager.Pref.serverUrl)
.client(okHttpClient)
.build()
}
fun sendDocument(@Path("id") id: Int, @Field("driver_comment") driverComment: String? = null, @Field("retrieved_at") retrievedAt: Date? = null): Single<ResponseBody>
我也试过这个序列化器:
class GsonIsoDateAdapter(private val timeZone: TimeZone = TimeZone.getTimeZone("UTC")) : JsonSerializer<Date>, JsonDeserializer<Date> {
private val iso8601Format: DateFormat
init {
this.iso8601Format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
this.iso8601Format.timeZone = timeZone
}
override fun serialize(src: Date?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
val dateFormatAsString = iso8601Format.format(src)
return JsonPrimitive(dateFormatAsString)
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Date {
if (json !is JsonPrimitive) {
throw JsonParseException("The date should be a string value")
}
val date = deserializeToDate(json)
return when {
typeOfT === Date::class.java -> date
typeOfT === java.sql.Date::class.java -> java.sql.Date(date.time)
else -> throw IllegalArgumentException(javaClass.toString() + " cannot deserialize to " + typeOfT)
}
}
private fun deserializeToDate(json: JsonElement): Date {
try {
return iso8601Format.parse(json.asString)
} catch (e: ParseException) {
throw JsonSyntaxException(json.asString, e)
}
}
}
但是当我'sendDocument'时,格式不是Gson使用的ISO8601,而是默认的日期格式。 setDateFormat 方法是否仅用于格式化接收日期?
谢谢
【问题讨论】: