Does GSon move temporary variables
I am trying to send a class over sockets and it all works fine. However, one of the variables gets messy for no apparent reason. Let me explain further.
The code I am using is the following (for the client socket where GSon is 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 containing two Strings
and Object[]
.
I tried Netbeans built-in debugger and these variables were present:
The ones highlighted in blue are the ones you should be looking at. As you can see, first there was a Timestamp object with a value 2013-02-18 15:49:36.415
that got converted to Feb 18, 2013 3:49:36PM
. Am I doing something wrong here? Is this a bug in GSon?
source to share
The Gson User Guide mentions this when it comes to creating custom serializers / deserializers. What you see is the default serialization for your object java.sql.Timestamp
(which is a subclass Date
) that should output / format it in a format for your locale.
If you look at the Javadoc for GsonBuilder () , you will find a method setDateFormat()
built specifically for your problem - it no longer requires a custom serializer. You just need to provide the template 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);
}
Conclusion (by right now, obviously):
2013-02-18 11: 32: 21,825
February 18, 2013 11:32:21 AM
"February 18, 2013 11:32:21"
"2013-02-18 11: 32: 21.825"
source to share
2013-02-18 15: 49: 36.415 which received Feb 18, 2013 3:49:36
and how are they different? It just looks like a rendering issue and your timestamp is converted to string using SimpleDateFormat or similar.
source to share