3

I have to send Date object to server through API (actually, Date is object that server is expecting). I want to use Moshi, but I can't figure out how to use Custom Adapter to make it happen. Anyone?

tristansokol
  • 4,054
  • 2
  • 17
  • 32
jean d'arme
  • 4,033
  • 6
  • 35
  • 70
  • 3
    `Date` is not something that is specified in JSON. So your server can't be expecting a Date object. It is expecting a certain representation of a Date, be it a string with a certain format, or a timestamp, or a complex structure. You need to start by figuring what format you are supposed to send, first. – njzk2 Sep 27 '16 at 15:27
  • I'm supposed to send JSON – jean d'arme Sep 27 '16 at 18:19
  • 2
    but `Date` has no meaning in the context of `JSON`. So that does not make sense. You have to figure out what format your server is expecting. – njzk2 Sep 27 '16 at 19:05

1 Answers1

3

Add a dependency on the moshi-adapters package:

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

Then install the Rfc3339DateJsonAdapter in your Moshi instance:

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

It’ll give you dates as JSON strings in RFC 3339 format, like this: "2017-05-06T20:00:00-05:00".

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • 3
    Any idea how to add this moshi instance to retrofit? – PrashanD May 12 '18 at 06:36
  • and what if the date isn't in Rfc3339 format? what if it looks like `2018-05-12T13:19:00Z` (ISO8601?) – noloman Sep 28 '19 at 11:30
  • RFC3339 supports dates that end with Z also. It is documented as a profile of ISO8601. – Jesse Wilson Sep 29 '19 at 12:05
  • 2
    @PrashanD adding moshi to retrofit (kotlin): `Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(Moshi.Builder().add(Date::class.java, Rfc3339DateJsonAdapter()).add(KotlinJsonAdapterFactory()).build()))` gradle dependencies: `implementation 'com.squareup.retrofit2:converter-moshi:2.4.0' implementation 'com.squareup.moshi:moshi-adapters:1.10.0' implementation 'com.squareup.moshi:moshi-kotlin:1.9.1'` – user1123432 Sep 19 '20 at 08:46