首页 > 解决方案 > 改造 + 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是否仅用于格式化接收日期?

谢谢

标签: androidgsonretrofit

解决方案


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


推荐阅读