I want to serialize a Map with Jackson.
The Date should be serialized as a timestamp, like all my other dates.
The following code renders the keys in the form “Tue Mar 11 00:00:00 CET 1952” (which is Date.toString()) instead of the timestamp.
Map<Date, String> myMap = new HashMap<Date, String>();
...
ObjectMapper.writeValue(myMap)
I assume this is because of type erasure and jackson doesn’t know at runtime that the key is a Date. But I didn’t find a way to pass a TypeReference to any writeValue method.
Is there a simple way to achieve my desired behaviour or are all keys always rendered as Strings by jackson?
Thanks for any hint.
The default map key serializer is
StdKeySerializer, and it simply does this.You could make use of the SimpleModule feature, and specify a custom key serializer, using the
addKeySerializermethod.And here’s how that could be done.
Update for the latest Jackson (2.0.4):