android - 改造 + Gson DateFormat 不起作用
问题描述
我会以 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是否仅用于格式化接收日期?
谢谢
解决方案
Try this solution. This is Java because I am not getting used to Kotlin yet:
Create a custom Gson JsonDeserializer
public class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context)
throws JsonParseException {
if (jsonElement == null)
return null;
String dateStr = jsonElement.getAsString();
try {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()).parse(dateStr);
} catch (ParseException ex) {
ex.printStackTrace();
}
return null;
}
}
Then in your createGsonInstance
, register both setDateFormat
and DateDeserializer
public static Gson createGsonInstance() {
return new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.registerTypeAdapter(Date.class, new DateDeserializer())
.excludeFieldsWithoutExposeAnnotation()
.create();
}
Use this Gson instance for Retrofit
推荐阅读
- c# - 无法分配给“arg”,因为它是“foreach 迭代变量”
- vue.js - VUE,在v-for循环中,如何在样式中绑定循环的各个url
- c# - 如何在 C# 中的 TextBox 中显示 ComboBox 选择?
- android - Firebase 依赖项因 Android Pie 和新的 androidx.* 包层次结构而失败
- python - 渲染灰度图像
- html - 时钟网格布局
- python - Pandas groupby 和 apply with unique 非常慢
- matrix - 如何在处理中的 applyMatrix 后找到新的 x,y,z?
- go - 将频道与 google pubsub poll 订阅者一起使用
- sql - SQL Server 触发器将更新的行复制到另一个历史表中