Does GSon mess up Timestamp variables

gson, java, timestamp

Solution

The Gson User's Guide mentions this when talking about creating custom serializers/deserializers. What you're seeing is the default serialization for your `java.sql.Timestamp` object (which is a subclass of `Date`) which is to output/format it in the format for your locale.

If you look at the Javadoc for GsonBuilder() you'll find a `setDateFormat()` method that was created specifically for your issue - it no longer requires a custom serializer. You just need to provide the pattern you want in your JSON:

public static void main(String[] args)
{
    Timestamp t = new Timestamp(System.currentTimeMillis());
    System.out.println(t);
    System.out.println(t.toLocaleString());
    String json = new Gson().toJson(t);
    System.out.println(json);
    json = new GsonBuilder()
               .setDateFormat("yyyy-MM-dd hh:mm:ss.S")
               .create()
               .toJson(t);

    System.out.println(json);
}    

Output (As of right now, obviously):

2013-02-18 11:32:21.825 Feb 18, 2013 11:32:21 AM "Feb 18, 2013 11:32:21 AM" "2013-02-18 11:32:21.825"

Problem

I'm trying to send a class over sockets, and this all works fine. However, one of the variables gets messed up for no apparent reason. Let me explain further. The code I'm using is the following (For the Client socket, where the GSon gets created): ``` while(!someQueueVariable.isEmpty()){ QueryHolder h = this.someQueueVariable.poll(); Gson g = new Gson(); String send = g.toJson(h); out.println(send); } ``` QueryHolder is a simple class that contains two `Strings` and an `Object[]`. I tried Netbeans' built-in Debugger, and these variables were present: The ones highlighted in blue are the ones you should look at. As you can see, there first was a Timestamp object with the value of `2013-02-18 15:49:36.415`, which got turned into `Feb 18, 2013 3:49:36PM`. Am I doing something wrong here? Is it a bug in GSon?

Original source