Skip to content Skip to sidebar Skip to footer

How To Deserialise .net Jsonresult Datetime Format With Gson In Android?

I have a JSON returned from server in this format: { 'StartDate': '/Date(1451593800000)/', 'EndDate': '/Date(1483216200000)/' } And in my POJO: public class Data { jav

Solution 1:

I have done some thing like this, Create a Date Serializer and register it to the GsonBuilder.

import java.lang.reflect.Type;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

publicclassDateDeserializerimplementsJsonDeserializer<Date> {

    @Overridepublic Date deserialize(JsonElement element, Type arg1,
            JsonDeserializationContext arg2) throws JsonParseException {
        String data = element.getAsString();
        data = data.replace("/Date(", "");
        data = data.replace(")/", "");
        try {
            return new Date(Long.parseLong(data));
        } catch (Exception e) {
            System.out.println("Failed to parse Date due to:");
            returnnull;
        }
    }
}

Registering with Gson Builder

Gson gson = new GsonBuilder().serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .registerTypeAdapter(Date.class, new DateDeserializer()).create();

Post a Comment for "How To Deserialise .net Jsonresult Datetime Format With Gson In Android?"