改造+ Gson DateFormat不起作用

时间:2018-07-09 07:33:18

标签: android gson retrofit

我将用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 是否仅用于格式化接收日期?

谢谢

1 个答案:

答案 0 :(得分:0)

尝试此解决方案。这是Java,因为我还不习惯Kotlin:

创建自定义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;
    }
}

然后在您的createGsonInstance中注册setDateFormatDateDeserializer

public static Gson createGsonInstance() {
    return new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .excludeFieldsWithoutExposeAnnotation()
            .create();
}

将此Gson实例用于翻新