【问题标题】:Retrofit + Gson DateFormat not work改造 + Gson DateFormat 不起作用
【发布时间】: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 方法是否仅用于格式化接收日期?

谢谢

【问题讨论】:

    标签: android gson retrofit


    【解决方案1】:

    试试这个解决方案。这是 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 实例进行改造

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 2018-04-18
      • 2018-04-02
      • 1970-01-01
      相关资源
      最近更新 更多