首页 > 解决方案 > 如何使用 Kotlin 和 Moshi 在 Android 中将 JSON 2019-04-28T00:00:00 格式转换为 GregorianCalender

问题描述

我有一个用 Kotlin 编写的 Android 应用程序,它从 JSON 获取数据。我使用 Retrofit 和 Moshi 来检索数据。我收到错误,因为 Moshi 不知道如何将日期转换为 GregorianCalendar。如何将 JSON 日期格式转换为 GregorianCalendar 格式?

JSON 日期格式如下:2000-06-28T00:00:00

API 配置:

class ApiClient {

    companion object {

        private const val BASE_URL = "http://10.0.2.2:3000"

        fun getClient(): Retrofit {
            val okHttpClient = OkHttpClient.Builder().build()
            val moshi = Moshi.Builder().build()

            return Builder().client(okHttpClient).baseUrl(BASE_URL)
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        }
    }
}

示例类:

data class Person (
  @Json(name = "personId")
  val personId: Int,

  @Json(name = "personName")
  val name: String,

  @Json(name = "personAge")
  val age: Int,

  @Json(name = "isFemale")
  val isFemale: Boolean,

  @Json(name = "birthDate")
  val birthDate: GregorianCalendar

)
{
  "persons": [{
      "personId": 1,
      "personName": "Bert",
      "personAge": 19,
      "isFemale": "false",
      "birthDate": "2000-06-28T00:00:00"
    }
  ]
}

我希望将 JSON 日期 2000-06-28T00:00:00 转换为 GregorianCalendar 或任何其他未被贬低但受最低 API21 支持的日期格式

标签: androiddatekotlingregorian-calendarmoshi

解决方案


推荐阅读