TL;DR:
My questions are:
1 - How can I make an Adapter
for the "timestamp": 1515375392.225
to ZonedDateTime
.
2 - How can I register the List<Report>
adapter in the moshi
object Builder
if I need the moshi object to get this adapter, according to the documentation?
My JSON string has the following structure:
[
{
"id": 0,
"location": {
"latitude": -22.967049,
"longitude": -43.19096
},
"timestamp": 1515375392.225
},
{
"id": 0,
"location": {
"latitude": -22.965845,
"longitude": -43.191102
},
"timestamp": 1515375392.225
},
.......
}]
The timestamp
is an automatic conversion made by the Jackson
JavaTimeModule
, it converts a ZonedDateTime
to a timestamp String
in the form of a decimal number representing the seconds
and nanoseconds
from an Instant
.
In order to parse the JSON timestamp String
, I made the following Moshi
adapter:
public class ZonedDateTimeAdapter {
@FromJson ZonedDateTime fromJson(String timestamp) {
int decimalIndex = timestamp.indexOf('.');
long seconds = Long.parseLong(timestamp.substring(0, decimalIndex));
long nanoseconds = Long.parseLong(timestamp.substring(decimalIndex));
return Instant.ofEpochSecond(seconds, nanoseconds).atZone(ZoneId.systemDefault());
}
@ToJson String toJson(ZonedDateTime zonedDateTime) {
Instant instant = zonedDateTime.toInstant();
return instant.getEpochSecond() + "." + instant.getNano();
}
}
And then I register this adapter as:
Type type = Types.newParameterizedType(List.class, Report.class);
Moshi moshi = new Moshi.Builder().add(new ZonedDateTimeAdapter()).build();
JsonAdapter<List<Report>> reportAdapter = moshi.adapter(type);
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build();
The problem is, when I call my webservice using Retrofit
, I get the following Exception
:
com.squareup.moshi.JsonDataException: java.lang.NumberFormatException: For input string: ".067000000" at $[0].timestamp
(keep in mind the nanoseconds .067000000 here won't be the same as the JSON example that I gave before, since they called the webservice at different times).
I tried to place a breakpoint on my ZonedDateTimeAdapter
, but it's never being called. But it's influencing Moshi, because if I remove it from the Moshi.Builder
, the error changes to:
Caused by: java.lang.IllegalArgumentException: Cannot serialize abstract class org.threeten.bp.ZoneId
I also tried to change the ZonedDateTimeAdapter
to deal with Double
instead of String
, but it just changes the error message to:
com.squareup.moshi.JsonDataException: java.lang.NumberFormatException: For input string: ".515376840747E9" at $[0].timestamp
So, basically, I have a bunch of changing error messages and no idea what am I doing wrong. I followed the Moshi documentation on Custom Adapters
and I don't know what else to do.