Converting Date to long during Json serialization

794 views
Skip to first unread message

Prashant Monteiro

unread,
Mar 27, 2013, 9:35:21 AM3/27/13
to googl...@googlegroups.com

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

bruce

unread,
Dec 9, 2013, 12:48:04 PM12/9/13
to googl...@googlegroups.com
Not sure whether this will help:
I had problem regarding date/time serialization in my python code using json; simply casting it to str worked instantly.
...
Reply all
Reply to author
Forward
0 new messages