Hi,
I am using Gson2.1 and Im trying to convert the Date to a long value during serialization, but the serialize method does not get invoked at all. I tried putting a break point in the serialize method of the Date serializer but execution never stops there.
Any ideas why this is happening? Here’s the code:
<code>
public static JsonElement toJsonElement(Object obj)
{
if(vomJson == null) {
GsonBuilder builder = new GsonBuilder();
// this will return all java.util.Date as long values.
builder.registerTypeHierarchyAdapter(java.util.Date.class, new JsonSerializer<java.util.Date>() {
@Override
public JsonElement serialize(java.util.Date date, Type typeOfDate, JsonSerializationContext context) {
return date == null ? null : new JsonPrimitive(date.getTime());
}
});
builder.registerTypeHierarchyAdapter(JsonSerializable.class, new JsonSerializer<JsonSerializable>()
{
@Override
public JsonElement serialize(JsonSerializable obj, Type typeOfSrc, JsonSerializationContext ctx)
{
return obj.toJson();
}
});
builder.setPrettyPrinting();
vomJson = builder.create();
}
return vomJson.toJsonTree(obj);
}
</code>
Any help will be appreciated.
Thanks,
Prashant