jackson serialize different time zones into single time zone - java

I have multiple timezones and I want to have them exactly after serialization, but jackson convert them into single time zone if I set DateFormat all zones convert to context time zone and if I don't set DateFormat all zones convert to UTC (zero time zone).
I know that we have DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE in deserialization and we can disable it but I can't find something like this in SerializationFeature.
Is there anyway that I can tell jackson to don't convert timezones?
here is my test class:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Test {
public static class flight {
private XMLGregorianCalendar dateDeparture;
private XMLGregorianCalendar dateArrival;
public XMLGregorianCalendar getDateDeparture() {
return dateDeparture;
}
public void setDateDeparture(XMLGregorianCalendar dateDeparture) {
this.dateDeparture = dateDeparture;
}
public XMLGregorianCalendar getDateArrival() {
return dateArrival;
}
public void setDateArrival(XMLGregorianCalendar dateArrival) {
this.dateArrival = dateArrival;
}
}
public static void main(String[] args) throws DatatypeConfigurationException, JsonProcessingException {
XMLGregorianCalendar dateDeparture = DatatypeFactory.newInstance().newXMLGregorianCalendar(2018,1,22,10,15,0,0, TimeZone.getTimeZone("Asia/Istanbul").getRawOffset()/1000/60);
XMLGregorianCalendar dateArrival = DatatypeFactory.newInstance().newXMLGregorianCalendar(2018,1,22,13,30,0,0,TimeZone.getTimeZone("Asia/Dubai").getRawOffset()/1000/60);
System.out.println("Local Departure Time=" + dateDeparture);
System.out.println("Local Arrival Time=" + dateArrival);
flight flight = new flight();
flight.setDateDeparture(dateDeparture);
flight.setDateArrival(dateArrival);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
xmlMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"));
String xml = xmlMapper.writeValueAsString(flight);
System.out.println(xml);
}
}
here is the output:
Local Departure Time=2018-01-22T10:15:00.000+03:00
Local Arrival Time=2018-01-22T13:30:00.000+04:00
<flight><dateDeparture>2018-01-22T10:45:00+0330</dateDeparture><dateArrival>2018-01-22T01:00:00+0330</dateArrival></flight>

The only way I could think of is to create your own serialize module so to be able to handle XMLGregorianCalendar serialization all by yourself. Unfortunately Java has proven not to be good in handling dates.
public class XMLCalendarSerializer extends StdSerializer<XMLGregorianCalendar> {
public XMLCalendarSerializer() {
this((Class)null);
}
public XMLCalendarSerializer(Class<XMLGregorianCalendar> t) {
super(t);
}
public void serialize(XMLGregorianCalendar value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
DateFormat dateFormatt = provider.getConfig().getDateFormat();
if(dateFormatt.getCalendar() == null) {
jgen.writeString(value.toString());
} else {
SimpleDateFormat dateFormat = (SimpleDateFormat)dateFormatt;
GregorianCalendar a = value.toGregorianCalendar();
Date date = value.toGregorianCalendar().getTime();
dateFormat.setTimeZone(TimeZone.getTimeZone(value.getTimeZone(value.getTimezone()).getDisplayName()));
jgen.writeString(dateFormat.format(date));
}
}
}
and the module class would be like:
public class XMLCalendarModule extends SimpleModule {
private static final String NAME = "CustomXMLCalendarModule";
private static final VersionUtil VERSION_UTIL = new VersionUtil() {
};
public XMLCalendarModule() {
super("CustomXMLCalendarModule", VERSION_UTIL.version());
this.addSerializer(XMLGregorianCalendar.class, new XMLCalendarSerializer());
}
}
and you can simply register this module like:
xmlMapper.registerModule(new XMLCalendarModule());

Related

Gson Serializer for a given class if in another specific class

I am trying to serialize (using Gson) a POJO and to have a special treatment for a single one of its fields.
Is it possible to do it in a simpler way than coding an adapter implementing JsonSerializer and having its serialize() method copy every field except for a specific one which receives the special treatment ?
Would it even be possible to make it using annotations in my POJO ?
I also cannot just write an adapter of the type of the specific field as it is a java.util.Date and I do not want every serialized Date to receive this treatment.
Here is an illustration :
public class Pojo {
#SerializedName("effectiveDate")
private final Date mDate;
#SerializedName("status")
private final Status mStatus; // <-- The field needing specific serialization
#SerializedName("details")
private final String mDetails;
// other fields
// methods
}
I would like to avoid coding an adapter as such :
public class PojoAdapter implements JsonSerializer<Pojo> {
#Override
public JsonElement serialize(final Pojo src, final Type typeOfSrc, final JsonSerializationContext context) {
final JsonObject jsonPojo = new JsonObject();
jsonDeployment.add("effectiveDate", /* special treatment */);
jsonDeployment.add("status", src.getStatus());
jsonDeployment.add("details", src.getDetails());
// other fields setting
return jsonPojo;
}
}
You can implement custom com.google.gson.JsonSerializer for a Date class and use com.google.gson.annotations.JsonAdapte annotation for given field to register it. See below example:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Type;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(new DatesPojo(new Date())));
}
}
class CustomDateJsonSerializer implements JsonSerializer<Date> {
#Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
String format = src.toInstant().atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ISO_TIME);
return new JsonPrimitive(format + " ISO TIME");
}
}
class DatesPojo {
#JsonAdapter(CustomDateJsonSerializer.class)
#SerializedName("customDate")
private final Date mDate0;
#SerializedName("effectiveDate")
private final Date mDate1;
public DatesPojo(Date mDate) {
this.mDate0 = mDate;
this.mDate1 = mDate;
}
public Date getmDate0() {
return mDate0;
}
public Date getmDate1() {
return mDate1;
}
}
Above code prints:
{
"customDate": "22:37:21.806+01:00 ISO TIME",
"effectiveDate": "Jan 22, 2020 10:37:21 PM"
}
I found another solution which consists in making my Date field implement an EffectiveDate interface which just extends Date and to add an adapter for this single field.

Serialize Java8 LocalDateTime to UTC Timestamp using Jackson

I've just converted over many of my Dates to LocalDateTime per the new(ish) java 8 time package. I've enjoyed the switch so far until I started trying to serialize and deserialize.
How can I configure Jackson to support them?:
LocalDateTime --serialize--> UTC Timestamp --deserialize--> LocalDateTime?
There's plenty of material on here about converting to formatted strings, but I can't seem to find an out-of-the-box solution to utc timestamps.
You can custom a serializer and a deserializer for LocalDateTime, for exmaple:
CustomLocalDateTimeSerializer
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
protected CustomLocalDateTimeSerializer(Class<LocalDateTime> t) {
super(t);
}
protected CustomLocalDateTimeSerializer() {
this(null);
}
#Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider sp)
throws IOException {
Long epoch = value.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
gen.writeString(epoch.toString());
}
}
CustomLocalDateTimeDesSerializer:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
class CustomLocalDateTimeDesSerializer extends StdDeserializer<LocalDateTime> {
protected CustomLocalDateTimeDesSerializer() {
this(null);
}
protected CustomLocalDateTimeDesSerializer(Class<LocalDateTime> t) {
super(t);
}
#Override
public LocalDateTime deserialize(JsonParser jsonparser, DeserializationContext context)
throws IOException {
Long timestamp = Long.parseLong(jsonparser.getText());
return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
And use the them:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDateTime;
public class RestObject {
private LocalDateTime timestamp = LocalDateTime.now();
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
#JsonDeserialize(using = CustomLocalDateTimeDesSerializer.class)
public LocalDateTime getTimestamp() {
return timestamp;
}
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
// {"timestamp":"1549026058"}
System.out.println(objectMapper.writeValueAsString(new RestObject()));
}
}
The following solution solves the task of serialize/deserialise the LocalDateTime to the timestamp and relevant at least for spring-boot v1.5 and also includes next points that are not taken into account in the #xingbin's answer:
If there is a necessity to have the same behaviour as for java.util.Date have to use the toInstant().toEpochMilli() instead the toInstant().getEpochSecond()
Check on null the value to deserialize
And optional point: specify this serialization/deserialization configuration for the Jackson ObjectMapper
The timestamp serializer class:
public class LocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeSerializer() {
super(LocalDateTime.class);
}
#Override
public void serialize(final LocalDateTime value,
final JsonGenerator generator,
final SerializerProvider provider) throws IOException {
if (value != null) {
final long mills = value.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
generator.writeNumber(mills);
} else {
generator.writeNull();
}
}
}
The timestamp deserializer class:
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public LocalDateTimeDeserializer() {
super(LocalDateTime.class);
}
#Override
public LocalDateTime deserialize(final JsonParser parser,
final DeserializationContext context) throws IOException {
final long value = parser.getValueAsLong();
return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), DEFAULT_ZONE_ID);
}
}
The object mapper configuration:
#Configuration
public class ObjectMapperConfiguration {
#Bean
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(module);
return objectMapper;
}
}
Instead of rewriting everything manually, you could leverage the JavaTimeModule:
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
Here is how to do it simply and efficiently:
#JsonFormat(shape= JsonFormat.Shape.STRING, pattern="EEE MMM dd HH:mm:ss Z yyyy")
#JsonProperty("created_at")
ZonedDateTime created_at;
This is a quote from a question: Jackson deserialize date from Twitter to `ZonedDateTime`, so this may be a duplicate question

Why is my DateTime deserializer is truncating DateTime's minute/second/millisecond?

I have a class that deserializes a JSON element.
public class DateTimeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime>
{
private static final DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.dateHourMinuteSecondMillis();
#Override
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context)
{
final DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinuteSecondMillis();
return new JsonPrimitive(fmt.print(src));
}
#Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
final String dateAsString = json.getAsString();
System.out.println(dateAsString);
if (json.isJsonNull() || dateAsString.length()==0)
{
return null;
}
else
{
return DATE_FORMAT.parseDateTime(json.getAsString());
}
}
}
However, my Deserialize method when I input:
2015-07-29T11:00:00.000Z
I receive:
2015-07-29T11
from the System.out.println(dateAsString); Why is it truncating my input?
I think my issue is within my test class:
I constructed a DateTime object to be used with Google's Gson. However, I think the default constructor for DateTimeType doesn't support minute/second/millisecond. Is there a way I can extend the DateTimeType to support it?
Here is my test class:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.joda.time.DateTime;
import org.junit.Test;
import java.lang.reflect.Type;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Tests {#link DateTimeConverter}.
*/
public class DateTimeConverterTest {
String testTime = "2015-07-29T11:00:00.001Z";
#Test
public void testDateTimeConverter() throws Exception {
final Gson gson = initCustomGSON();
Type DateTimeType = new TypeToken<DateTime>() {
}.getType();
System.out.println(testTime);
DateTimeConverter timeConverter = new DateTimeConverter();
DateTime m = (gson.fromJson(testTime, DateTimeType));
assertThat("11", is(m.hourOfDay().getAsText()));
}
public Gson initCustomGSON() {
final GsonBuilder builder = new GsonBuilder();
JodaTimeConverters converter = new JodaTimeConverters();
converter.registerAll(builder);
return builder.create();
}
}
You have a few issues with this code.
Your first problem is that : is an operator in Json. You are interpreting an unescaped String with a : in it, so Gson is interpreting it as key : value. Your test string needs to surround the entire text date with quotes to prevent this from happening, e.g.
String testTime = "\"2015-07-29T11:00:00.001Z\"";
You were using ISODateTimeFormat.dateHourMinuteSecondMillis() in your code. However, the format pattern for this is yyyy-MM-dd'T'HH:mm:ss.SSS, which as you can see does not include a time zone. You want to be using ISODateTimeFormat.dateTime(), whose pattern is yyyy-MM-dd'T'HH:mm:ss.SSSZZ, which does have a time zone.
private static final DateTimeFormatter DATE_FORMAT = ISODateTimeFormat.dateTime();
Once these two changes are made, the DateTime object is finally properly created... but it will be created in your local time zone, not in UTC (it will correctly adjust the time to your zone. You can easily switch this back to UTC by doing:
DateTime m = ((DateTime) (gson.fromJson(testTime, DateTimeType))).withZone(DateTimeZone.UTC);
Once you make these three changes, your tests will pass. However: I strongly advise against using JsonSerializer and JsonDeserializer, they have been deprecated in favor of TypeAdapter, whose streaming API is significantly more performant:
New applications should prefer TypeAdapter, whose streaming API is more efficient than this interface's tree API.
I am aware the user guide provides code for how to do it with the JsonSerializer / JsonDeserializer API, but that's just because they haven't yet updated it.
It would simply be something like this:
public class DateTimeAdapter extends TypeAdapter<DateTime> {
private static final DateTimeFormatter FORMAT = ISODateTimeFormat.dateTime();
public DateTime read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String dateString = reader.nextString();
if(dateString.length() == 0) return null;
return FORMAT.parseDateTime(dateString);
}
public void write(JsonWriter writer, DateTime value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(FORMAT.print(value));
}
}

Jackson De/Serializing Date-to-String-to-Date in generic Maps

There are many examples of Jackson to/from java.util.Date code but they all seem to leverage POJO annotation. I have generic Maps of scalars that I wish to de/serialize to JSON. This is the current deserializer setup; very simple:
public class JSONUtils {
static {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
mapper.setDateFormat(df); // this works for outbounds but has no effect on inbounds
mapper.getDeserializationConfig().with(df); // Gave this a shot but still does not sniff strings for a format that we declare should be treated as java.util.Date
}
public static Map<String,Object> parseJSON(InputStream is) {
Map<String,Object> data = null;
try {
data = mapper.readValue(is, Map.class);
} catch(Exception e) {
// ...
}
return data;
}
I grok that a dateserializer can turn java.util.Date into a ISO 8601-ish string. It's going the other way that puzzles me. Clearly, in a JSON doc with no context, a string is a string so I cannot know if it was once a date. So I am prepared to duck type this and examine all strings being deserialized and if they smell like YYYY-MM-DDTHH:MM:SS.sss datetimes, then I will make a java.util.Date instead of just passing back a String. So given:
{ "name": "buzz",
"theDate": "2013-09-10T12:00:00.000"
}
will yield
Map<String,Object> m = mapper.readValue(is, Map.class);
Object o1 = m.get("name"); // o1 is instanceof String
Object o2 = m.get("theDate"); // o2 is instanceof Date
But this means that the deserializer has to return two different types and I have not been able to figure out how to do this in Jackson. Does anyone know of a good, compact example that will sniff for date-like strings and turn them into Dates, leaving others as Strings?
I've been looking for the answer on a related subject recently and come up with the following solution, thanks to Justin Musgrove and his article Custom jackson date deserializer.
Basically, the idea is to replace standard deserializer for Object.class that will convert any string in the specified format to the Date object or fallback to the standard behaviour otherwise. Obviously, this operation comes at cost of extra processing, so you'd want to keep a dedicated instance of ObjectMapper configured for this and only use it when absolutely necessary or if prepared doing second pass anyway.
Note that the Date string format in your example has no timezone component, which may cause some issues, but I leave the format as requested. You can use a parser of your choice in place of the FastDateFormat from Apache Commons Lang. I actually use Instant in my case.
CustomObjectDeserializer.java
import java.io.IOException;
import org.apache.commons.lang3.time.FastDateFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;
public class CustomObjectDeserializer extends UntypedObjectDeserializer {
private static final long serialVersionUID = 1L;
private static final FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS");
public CustomObjectDeserializer() {
super(null, null);
}
#Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
if (p.getCurrentTokenId() == JsonTokenId.ID_STRING) {
try {
String value = p.getText();
// put your own parser here
return format.parse(value);
} catch (Exception e) {
return super.deserialize(p, ctxt);
}
} else {
return super.deserialize(p, ctxt);
}
}
}
JSONUtils.java
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JSONUtils {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
SimpleModule module = new SimpleModule("DateConverter");
// register a new deserializer extending and replacing UntypedObjectDeserializer
module.addDeserializer(Object.class, new CustomObjectDeserializer());
mapper.registerModule(module);
}
public static Map<String, Object> parseJSON(InputStream is) {
Map<String, Object> data = null;
try {
data = mapper.readValue(is, Map.class);
} catch (Exception e) {
// ...
e.printStackTrace();
}
return data;
}
public static void main(String[] args) throws Exception {
String input = "{\"name\": \"buzz\", \"theDate\": \"2013-09-10T12:00:00.000\"}";
InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
Map<String, Object> m = mapper.readValue(is, Map.class);
Object o1 = m.get("name"); // o1 is instanceof String
Object o2 = m.get("theDate"); // o2 is instanceof Date
System.out.println(o1.getClass().getName() + " : " + o1);
System.out.println(o2.getClass().getName() + " : " + o2);
}
}
If you have a POJO, you can easy use annotation on get and set method with serializer and deserializer.
following an example that serialize and deserialize objects in different ways: List<POJO> to String, String to Map and Map to List<POJO> again. Obviously, in the map the Date values are as String.
This solution is thread safe because uses org.joda.time.format.DateTimeFormat and org.joda.time.format.DateTimeFormatter, you can find more info herein this post How to deserialize JS date using Jackson? and this link http://fahdshariff.blogspot.co.uk/2010/08/dateformat-with-multiple-threads.html
My POJO:
#JsonAutoDetect
public class QueueTask implements Serializable {
private static final long serialVersionUID = -4411796657106403937L;
public enum ActivitiQueueStatus {
IN_PROGRESS(AsyncProcessingWorkflowContentModel.InProgressTask.TYPE.getLocalName()), //
IN_QUEUE(AsyncProcessingWorkflowContentModel.InQueueTask.TYPE.getLocalName());
private String value;
private ActivitiQueueStatus(final String value) {
this.value = value;
}
public static ActivitiQueueStatus enumOf(final String value) {
for (ActivitiQueueStatus enum_i : values()) {
if (enum_i.value.equals(value))
return enum_i;
}
throw new IllegalArgumentException("value '" + value + "' is not a valid enum");
}
}
private String user;
private Date creationDate;
private int noRowsSelected;
private ActivitiQueueStatus status;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
#JsonSerialize(using = JsonDateSerializer.class)
public Date getCreationDate() {
return creationDate;
}
#JsonDeserialize(using = JsonDateDeSerializer.class)
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public int getNoRowsSelected() {
return noRowsSelected;
}
public void setNoRowsSelected(int noRowsSelected) {
this.noRowsSelected = noRowsSelected;
}
public ActivitiQueueStatus getStatus() {
return status;
}
public void setStatus(ActivitiQueueStatus status) {
this.status = status;
}
}
My Serializer:
#Component
public class JsonDateDeSerializer extends JsonDeserializer<Date> {
// use joda library for thread safe issue
private static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd/MM/yyyy hh:mm:ss");
#Override
public Date deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
if (jp.getCurrentToken().equals(JsonToken.VALUE_STRING))
return dateFormat.parseDateTime(jp.getText().toString()).toDate();
return null;
}
}
and Deserializer:
#Component
public class JsonDateSerializer extends JsonSerializer<Date> {
// use joda library for thread safe issue
private static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd/MM/yyyy hh:mm:ss");
#Override
public void serialize(final Date date, final JsonGenerator gen, final SerializerProvider provider) throws IOException, JsonProcessingException {
final String formattedDate = dateFormat.print(date.getTime());
gen.writeString(formattedDate);
}
}
My Service:
public class ServiceMock {
// mock this parameter for usage.
public List<QueueTask> getActiveActivities(QName taskStatus) {
final List<QueueTask> listToReturn = new LinkedList<QueueTask>();
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date d1 = null, d2 = null, d3 = null, d4 = null, d5 = null;
try {
d1 = dateFormat.parse("01/02/2013 12:44:44");
d2 = dateFormat.parse("21/12/2013 16:44:44");
d3 = dateFormat.parse("21/12/2013 16:45:44");
d4 = dateFormat.parse("21/12/2013 16:44:46");
d5 = dateFormat.parse("11/09/2013 16:44:44");
} catch (ParseException e) {
}
QueueTask dataSet = new QueueTask();
dataSet = new QueueTask();
dataSet.setUser("user_b");
dataSet.setStatus(ActivitiQueueStatus.enumOf("placeInQueue"));
dataSet.setNoRowsSelected(500);
dataSet.setCreationDate(d1);
listToReturn.add(dataSet);
dataSet = new QueueTask();
dataSet.setUser("user_d");
dataSet.setStatus(ActivitiQueueStatus.enumOf("placeInQueue"));
dataSet.setNoRowsSelected(300);
dataSet.setCreationDate(d2);
listToReturn.add(dataSet);
dataSet = new QueueTask();
dataSet.setUser("user_a");
dataSet.setStatus(ActivitiQueueStatus.enumOf("inProgress"));
dataSet.setNoRowsSelected(700);
dataSet.setCreationDate(d3);
listToReturn.add(dataSet);
dataSet = new QueueTask();
dataSet.setUser("user_k");
dataSet.setStatus(ActivitiQueueStatus.enumOf("inProgress"));
dataSet.setNoRowsSelected(700);
dataSet.setCreationDate(d4);
listToReturn.add(dataSet);
dataSet = new QueueTask();
dataSet.setUser("user_l");
dataSet.setStatus(ActivitiQueueStatus.enumOf("inProgress"));
dataSet.setNoRowsSelected(700);
dataSet.setCreationDate(d5);
listToReturn.add(dataSet);
return listToReturn;
}
}
MAIN usage:
public class SerializationServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(OUPQueueStatusServiceIT.class);
public void testGetActiveActivitiesSerialization() throws Exception {
LOGGER.info("testGetActiveActivitiesSerialization - start");
ServiceMock mockedService = new ServiceMock();
// AsyncProcessingWorkflowContentModel.InProgressTask.TYPE is an QName, mock this calling
List<QueueTask> tasks = mockedService.getActiveActivities(AsyncProcessingWorkflowContentModel.InProgressTask.TYPE);
assertNotNull(tasks);
assertTrue(tasks.size() == 5);
assertNotNull(tasks.get(0).getUser());
assertNotNull(tasks.get(0).getCreationDate());
assertNotNull(tasks.get(0).getStatus());
assertNotNull(tasks.get(0).getNoRowsSelected());
final ObjectMapper mapper = new ObjectMapper();
final String jsonString = mapper.writeValueAsString(tasks);
assertNotNull(jsonString);
assertTrue(jsonString.contains("creationDate"));
// test serialization from string to Map
final List<Map<String, Object>> listOfMap = mapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>() {
});
assertNotNull(listOfMap);
final DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
for (Map<String, Object> map_i : listOfMap) {
// check date value
assertTrue(map_i.containsKey("creationDate"));
final Date date = formatter.parse("" + map_i.get("creationDate"));
assertNotNull(date);
assertNotNull(map_i.get("user"));
assertNotNull(map_i.get("status"));
assertNotNull(ActivitiQueueStatus.valueOf("" + map_i.get("status")));
assertNotNull(map_i.get("noRowsSelected"));
}
// test de-serialization
List<QueueTask> deserializedTaskList = mapper.convertValue(listOfMap, new TypeReference<List<QueueTask>>() {
});
assertNotNull(deserializedTaskList);
assertTrue(deserializedTaskList.size() == 5);
for (QueueTask t : deserializedTaskList) {
assertNotNull(t.getUser());
assertNotNull(t.getCreationDate());
assertNotNull(t.getDownloadType());
assertNotNull(t.getStatus());
}
LOGGER.info("testGetActiveActivitiesSerialization - end");
}
public static void main(String[] args) throws Exception {
new SerializationServiceTest().SerializationServiceTest();
}
}
After some weeks poking around on this (and no other comments or answers), I now believe what I seek is NOT possible in Jackson. Deserialization of JSON into a Map with ducktyping for dates must occur after-the-fact. There is no way to interpose the parse stream, sniff the string for YYYY-MM-DDTHH:MM:SS.SSS and upon match substitute a Date object instead of String. You must let Jackson build the Map, then outside of Jackson go back to the top and walk the Map, sniffing for dates.
I will add that since I have a very specific duck I am looking for, the fastest implementation to turn the String into a Date is a hand-rolled thing about 120 lines long that validates and sets up the proper integer m-d-y-h-m-s-ms for Calendar then calls getTime(). 10,000,000 conversions takes 4240 millis, or about 2.3m/sec.
Before the joda-time lobby pipes up, yes, I tried that first:
// This is set up ONCE, outside the timing loop:
DateTimeFormatter format = ISODateTimeFormat.dateHourMinuteSecondMillis();
// These are in the timing loop:
while(loop) {
DateTime time = format.parseDateTime("2013-09-09T14:45:00.123");
Date d = time.toDate();
}
takes about 9630 millis to run, about 1.04m/sec; half the speed. But that's still WAY faster than the "out of the box use javax" option:
java.util.Calendar c2 = javax.xml.bind.DatatypeConverter.parseDateTime(s);
Date d = c2.getTime();
This takes 30428 mills to run, about .33m/sec -- almost 7x slower than the handroll.
SimpleDateFormat is not thread-safe so therefore was not considered in for use in converter utility where I cannot make any assumptions about the callers.
Here is a basic example on how to use Jackson to serialize deserialize a date from an object
public class JacksonSetup {
private static class JacksonSerializer {
private static JacksonSerializer instance;
private JacksonSerializer() {
}
public static JacksonSerializer getInstance() {
if (instance == null)
instance = new JacksonSerializer();
return instance;
}
public <E extends ModelObject> void writeTo(E object, Class<E> type, OutputStream out) throws IOException {
ObjectMapper mapper = getMapper();
mapper.writeValue(out, object);
}
public <E extends ModelObject> void writeTo(E object, Class<E> type, Writer out) throws IOException {
ObjectMapper mapper = getMapper();
mapper.writeValue(out, object);
}
public <E extends ModelObject> E read(String input, Class<E> type) throws IOException {
ObjectMapper mapper = getMapper();
E result = (E) mapper.readValue(input, type);
return result;
}
private ObjectMapper getMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector);
return mapper;
}
}
private static class JaxbDateSerializer extends XmlAdapter<String, Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
#Override
public String marshal(Date date) throws Exception {
return dateFormat.format(date);
}
#Override
public Date unmarshal(String date) throws Exception {
return dateFormat.parse(date);
}
}
private static abstract class ModelObject {
}
private static class Person extends ModelObject {
private String name;
private Date bday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement(name = "birth-day")
#XmlJavaTypeAdapter(JaxbDateSerializer.class)
public Date getBday() {
return bday;
}
public void setBday(Date bday) {
this.bday = bday;
}
}
public static void main(String[] args) {
try {
Person person = new Person();
person.setName("Jhon Doe");
person.setBday(new Date());
Writer writer = new StringWriter();
JacksonSerializer.getInstance().writeTo(person, Person.class, writer);
System.out.println(writer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to change programmatically the default JAXB date serialization?

Is there a way to change the default way jaxb serialize/deserialize types, dates in my case, without specifying it through annotation and/or through xml jaxb binding as mentioned here
http://jaxb.java.net/guide/Using_different_datatypes.html
I'd basically like to do something like:
JAXBContext jaxbContext = ...;
Marshaller marshaller = jaxbContext.createMarshaller().setAdapter(new DateAdapter(dateFormat));
To have a preconfigured JaxBContext or Marshaller/Unmarshaller that serialize/deserialize dates in a customized way..
Couldn't find any resource that shows how to do expect through annotations or statically with the xml binding file..
Thanks!
This isn't exactly what you're looking for but it beats annotating every Date field individually. You can set a XmlJavaTypeAdapter at the package level so that every reference to Date within your package will use it. If your objects are in the com.example package, you should add a package-info.java file to it with the following contents:
#XmlJavaTypeAdapter(value=MyCustomDateAdapter.class,type=Date.class)
package com.example;
Try this:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement(name = "event")
public class Event {
private Date date;
private String description;
#XmlJavaTypeAdapter(DateFormatterAdapter.class)
public Date getDate() {
return date;
}
public void setDate(final Date date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
private static class DateFormatterAdapter extends XmlAdapter<String, Date> {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd_mm_yyyy");
#Override
public Date unmarshal(final String v) throws Exception {
return dateFormat.parse(v);
}
#Override
public String marshal(final Date v) throws Exception {
return dateFormat.format(v);
}
}
public static void main(final String[] args) throws Exception {
final JAXBContext context = JAXBContext.newInstance(Event.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
final Event event = new Event();
event.setDate(new Date());
event.setDescription("im rick james");
marshaller.marshal(event, System.out);
}
}
This produces:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<event>
<date>16_05_2011</date>
<description>im rick james</description>
</event>
After searching whole jaxb documentation and many tutorials, I did not find any answer that can configure dates apart from what we hard code in XMLAdapter.
I put a property file in classpath having date formats as for example:
dateFormat=mm-dd-YYYY
Now your XMLAdapter implementation goes as below:
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ConfigurableAdapterForDate extends XmlAdapter<String, Date>{
private static final String FORMAT = "yyyy-mm-dd";
private String formatFromFile = null;
private SimpleDateFormat format = new SimpleDateFormat();
private void setFormatFromFile() throws IOException {
//load property file
Properties prop = new Properties();
InputStream is = this.getClass().getResourceAsStream("<path to your property file>");
prop.load(is);
//get the format from loaded property file
formatFromFile = prop.getPropertyValue("dateFormat");
if(formatFromFile != null) {
format.applyPattern(formatFromFile);
}
else {
format.applyPattern(FORMAT );
}
}
#Override
public Date unmarshal(String v) throws Exception {
this.setFormatFromFile();
return format.parse(v);
}
#Override
public String marshal(Date v) throws Exception {
this.setFormatFromFile();
return format.format(v);
}
}
Now you can use #XmlJavaTypeAdapter(ConfigurableAdapterForDate.class)for date objects which you want to serialize/deserialize.
One is free to use spring also to load property file. Above code will configure your date accordingly.

Categories