I am using the Retrofit library for my REST calls. The JSON that is coming in looks like this.
{
"created_at": "2013-07-16T22:52:36Z",
}
How can I tell Retrofit or Gson to convert this into long?
You can easily do this by setting a custom GsonConverter with your own Gson object on the retrofit instance. In your POJO you can Date created_at;
instead of a long or a String. From the date object you can use created_at.getTime()
to get the long when necessary.
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
.create();
RestAdapter.Builder builder = new RestAdapter.Builder();
// Use a custom GSON converter
builder.setConverter(new GsonConverter(gson));
..... create retrofit service.
You can also support multiple Date string formats by registering a custom JsonDeserializer
on the gson instance used by retrofit
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
public class DateTypeDeserializer implements JsonDeserializer<Date> {
private static final String[] DATE_FORMATS = new String[]{
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd",
"EEE MMM dd HH:mm:ss z yyyy",
"HH:mm:ss",
"MM/dd/yyyy HH:mm:ss aaa",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'",
"MMM d',' yyyy H:mm:ss a"
};
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: \n" + Arrays.toString(DATE_FORMATS));
}
}
Read it in as a string in your POJO then use your getter to return it as a long:
String created_at;
public long getCreatedAt(){
SimpleDateFormat formatter = new
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date createDate = formatter.parse(created_at);
return createDate.getTime();
}
the SimpleDateFormat string can be referenced here
You could simply use this setDateFormat()
method to do it
public class RestClient
{
private static final String BASE_URL = "your base url";
private ApiService apiService;
public RestClient()
{
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(BASE_URL)
.setConverter(new GsonConverter(gson))
.build();
apiService = restAdapter.create(ApiService.class);
}
public ApiService getApiService()
{
return apiService;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With