Details
-
Type:
New Feature
-
Status:
Resolved
-
Priority:
Minor
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: None
-
Component/s: None
-
Labels:None
-
Number of attachments :
Description
When serializing a Map with keys of type java.util.Date, Jackson should have a feature to allow the user to easily specify the format of the date value representation. The current solution available to users is to implement custom serialization, with 8-12 lines of boilerplate code (including setup of a SimpleModule), and 1 line that performs the value transformation. The preferred solution would reduce coding requirements to 1-2 lines.
A reasonable approach that would also not break any existing client code base, would be to add a SerializationConfig.Feature, off by default, which I'll call WRITE_FORMATTED_DATES_AS_MAP_KEYS for now. It would essentially turn on/off whether Date Map keys serialize in the same format as Date values.
The following demonstrates such a new feature in action.
Date date = new Date(); Map<Date, String> map = new HashMap<Date, String>(); map.put(date, "now"); System.out.println(date); // Tue Jul 05 13:48:09 MST 2011 System.out.println(map); // {Tue Jul 05 13:50:16 MST 2011=now} ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(date)); // 1309898889090 System.out.println(mapper.writeValueAsString(map)); // {"Tue Jul 05 13:50:16 MST 2011":"now"} mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); System.out.println(mapper.writeValueAsString(date)); // "2011-07-05T20:48:09.090+0000" System.out.println(mapper.writeValueAsString(map)); // {"Tue Jul 05 13:50:16 MST 2011":"now"} mapper.setSerializationConfig(mapper.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy.MM.dd"))); System.out.println(mapper.writeValueAsString(date)); // "2011.07.05" System.out.println(mapper.writeValueAsString(map)); // {"Tue Jul 05 13:58:54 MST 2011":"now"} mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.WRITE_FORMATTED_DATES_AS_MAP_KEYS, true); System.out.println(mapper.writeValueAsString(date)); // 1309904306583 System.out.println(mapper.writeValueAsString(map)); // {"1309904306583":"now"} mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); System.out.println(mapper.writeValueAsString(date)); // "2011-07-05T22:19:20.170+0000" System.out.println(mapper.writeValueAsString(map)); // {"2011-07-05T22:19:20.170+0000":"now"} mapper.setSerializationConfig(mapper.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy.MM.dd"))); System.out.println(mapper.writeValueAsString(date)); // "2011.07.05" System.out.println(mapper.writeValueAsString(map)); // {"2011.07.05":"now"}
Makes sense to me.