Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson Deserializer for java.util.Date

Does anyone got Deserializer working?

I'm getting complete JSON expression in method deserialize instead of element?

public static void main(String[] args) {
    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(DummyObject.class, new JsonSerializer<Date>() {
        public JsonElement serialize(Date src, Type typeOfSrc, 
                         JsonSerializationContext context) {
            System.out.println("serialize...");
            return new JsonPrimitive(DateUtil.toString(src));
        }
    });
    gb.registerTypeAdapter(DummyObject.class, new JsonDeserializer<Date>() {
        DateFormat format = DateFormat.getInstance();
        public Date deserialize(JsonElement json, Type typeOfT, 
                         JsonDeserializationContext context) throws JsonParseException {
            if (!(json instanceof JsonPrimitive)) {
                throw new JsonParseException("The date should be a string value");
            }
            try {
                return format.parse(json.getAsString());
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
    });
    String jsonExp = "{\"createdDate\":\"2011-12-27T15:21:16\"}";
    Gson g = gb.create();
    DummyObject tf = g.fromJson(jsonExp, DummyObject.class);
}
like image 975
gpa Avatar asked Dec 28 '11 01:12

gpa


1 Answers

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
.create();
like image 196
Paul Burke Avatar answered Nov 27 '22 21:11

Paul Burke