jackson-dataformat-xml
jackson-dataformat-xml copied to clipboard
Deserialization empty timestamps fields to null value doesn't work
Hi. From version 2.12.0 deserialization timestamps works in other way. I have field in model:
@JacksonXmlProperty(isAttribute = true,localName = "timestampDate")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Timestamp timestampDate;
In response i receive something like this:
<PositionsCurrent>
<PositionsCurrent timestampDate="" />
</PositionsCurrent>
Earlier this assertion worked fine:
Assert.assertNull(response.getData());
On the newest version 2.14 deserialization returns something like this:
Actual :1970-01-01 01:00:00.0
Is it possible to return null again when I try deserialize empty field to Timestamp?
@silvestr85 Try enabling FromXmlParser.EMPTY_ELEMENT_AS_NULL.
Handling of empty String to "empty" Timestamp is indeed unfortunate and shouldn't occur.
If nothing else works you could alternatively add/override setTimestamp(Timestamp ts) method and look if underlying epoch value (long) is 0L and if so translate instance into null.
ps. which Timestamp class are we talking about? java.sql.Timestamp?
I was trying this one FromXmlParser.EMPTY_ELEMENT_AS_NULL but it doesn't work for Timestamp.
Yes, I'm using java.sql.Timestamp
For now I have workaround as my own converter:
public class TimestampConverter extends StdConverter<String, Timestamp> {
@Override
public Timestamp convert(final String value) {
if (value == null || value.equals("")) {
return null;
}
else {
return Timestamp.valueOf(value);
}
}
}
FWTW, I think this is unfortunately something that happens, as jackson-databind has TimestampDeserializer that indicates that so-called "empty" value is one with instance constructed with timestamp of 0L -- which means January 1st, 1970, UTC (epoch).
So I think work-around indicated makes sense.
I found the solution 🥳
You must set the behaviour of coercionConfigFor:
XmlMapper mapper = new XmlMapper();
mapper.coercionConfigFor( LogicalType.DateTime ).setCoercion( CoercionInputShape.EmptyString, CoercionAction.AsNull );