21

与 Gson 你会这样做

Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm")
            .create();

并将其传递给改造构建器,Gson 会为您创建一个 Date 对象,Moshi在 kotlin 类中是否也有一些方法可以做到这一点?

4

2 回答 2

46

如果您想使用标准 ISO-8601/RFC 3339 日期适配器(您可能会这样做),那么您可以使用内置适配器:

Moshi moshi = new Moshi.Builder()
    .add(Date.class, new Rfc3339DateJsonAdapter().nullSafe())
    .build();

JsonAdapter<Date> dateAdapter = moshi.adapter(Date.class);
assertThat(dateAdapter.fromJson("\"1985-04-12T23:20:50.52Z\""))
    .isEqualTo(newDate(1985, 4, 12, 23, 20, 50, 520, 0));

您将需要此 Maven 依赖项才能使其工作:

<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi-adapters</artifactId>
  <version>1.5.0</version>
</dependency>

如果您想使用自定义格式(您可能不会),还有更多代码。编写一个接受日期并将其格式化为字符串的方法,以及另一个接受字符串并将其解析为日期的方法。

Object customDateAdapter = new Object() {
  final DateFormat dateFormat;
  {
    dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  }

  @ToJson synchronized String dateToJson(Date d) {
    return dateFormat.format(d);
  }

  @FromJson synchronized Date dateToJson(String s) throws ParseException {
    return dateFormat.parse(s);
  }
};

Moshi moshi = new Moshi.Builder()
    .add(customDateAdapter)
    .build();

JsonAdapter<Date> dateAdapter = moshi.adapter(Date.class);
assertThat(dateAdapter.fromJson("\"1985-04-12T23:20\""))
    .isEqualTo(newDate(1985, 4, 12, 23, 20, 0, 0, 0));

您需要记住使用synchronized,因为SimpleDateFormat它不是线程安全的。您还需要为SimpleDateFormat.

于 2017-06-10T21:16:17.330 回答
16

在 kotlin 中,您可以扩展JsonAdapter类并创建自己的适配器:

class CustomDateAdapter : JsonAdapter<Date>() {
    private val dateFormat = SimpleDateFormat(SERVER_FORMAT, Locale.getDefault())

    @FromJson
    override fun fromJson(reader: JsonReader): Date? {
        return try {
            val dateAsString = reader.nextString()
            synchronized(dateFormat) {
                dateFormat.parse(dateAsString)
            }
        } catch (e: Exception) {
            null
        }
    }

    @ToJson
    override fun toJson(writer: JsonWriter, value: Date?) {
        if (value != null) {
            synchronized(dateFormat) {
                writer.value(value.toString())
            }
        }
    }

    companion object {
        const val SERVER_FORMAT = ("yyyy-MM-dd'T'HH:mm") // define your server format here
    }
}

然后,在改造初始化中,您可以通过以下方式设置适配器Moshi.Builder

 private val moshiBuilder = Moshi.Builder().add(CustomDateAdapter()) // Your custom date adapter here

        val service: ApiService by lazy {
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

            val httpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build()

            val retrofit = Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL)
                .client(httpClient)
                .addConverterFactory(MoshiConverterFactory.create(moshiBuilder.build())) // And don`t forget to add moshi class when creating MoshiConverterFactory 
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .build()

            retrofit.create(ApiService::class.java)
        }
于 2019-07-08T15:43:46.833 回答