0

I have an Android App written in Kotlin, that gets data from JSON. I use Retrofit and Moshi to retrieve the data. I receive errors because Moshi does not know how to convert a date to GregorianCalendar. How can I convert the JSON date format to the GregorianCalendar format?

The JSON date is in the following format: 2000-06-28T00:00:00

The API configuration:

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()
        }
    }
}

Example class:

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"
    }
  ]
}

I want the JSON date 2000-06-28T00:00:00 to be converted to GregorianCalendar or any other Date format that is not depricated but supported by minimum API21

Walt
  • 111
  • 1
  • 2
  • 12
  • 2
    I think this will help you out https://stackoverflow.com/questions/44464550/turn-string-date-from-json-to-a-date-object-with-moshi – Varun Malhotra May 02 '19 at 10:44
  • @VarunMalhotra that's for date which is depricated. – Walt May 02 '19 at 11:14
  • 1
    If you are going to work with date/times, you should probably use [ThreeTenABP](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project) or the standard [SDK from API 26](https://developer.android.com/reference/java/time/LocalDateTime): `LocalDateTime.parse(birthDate)`. – assylias May 02 '19 at 11:19
  • @assylias I need to support API 21 as a minimum – Walt May 02 '19 at 11:27
  • Possible duplicate of [Turn string date from json to a Date object with Moshi](https://stackoverflow.com/questions/44464550/turn-string-date-from-json-to-a-date-object-with-moshi) – shkschneider May 02 '19 at 11:40
  • 1
    Yes, we got that about minimum level 21. That’s why @assylias referred you to ThreeTenABP. Please go ahead. – Ole V.V. May 02 '19 at 12:35

0 Answers0