Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit GSON serialize Date from json string into long or java.lang.Long

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?

like image 672
user2524597 Avatar asked Feb 16 '15 11:02

user2524597


3 Answers

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));
    }
}
like image 155
Aegis Avatar answered Oct 30 '22 20:10

Aegis


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

like image 5
pula Avatar answered Oct 30 '22 21:10

pula


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;
    }
}
like image 3
Gowtham Raj Avatar answered Oct 30 '22 20:10

Gowtham Raj