Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GSon mess up Timestamp variables

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: Variables 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?

like image 973
Lolmewn Avatar asked Feb 18 '13 15:02

Lolmewn


2 Answers

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"

like image 187
Brian Roach Avatar answered Sep 24 '22 19:09

Brian Roach


2013-02-18 15:49:36.415, which got turned into Feb 18, 2013 3:49:36PM

and these are different how ? This simply looks like a rendering issue and your timestamp is being converted to a string via a SimpleDateFormat or similar.

like image 39
Brian Agnew Avatar answered Sep 22 '22 19:09

Brian Agnew