0

I'm trying to parse timestamps in the RFC3339 format in a JSON-string using Jackson. How do I allow for the variable amount of decimal places after the seconds?

For the JSON file

{
    "timestamp": "2019-07-02T13:00:34.836+02:00"
}

I've deserialized it with the class

public abstract class Attribute {
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
    public Date timestamp;
}

and an ObjectMapper with the JavaTimeModule:

ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
mapper.readValue(jsonFile, Attribute.class);

This works fine. However, it should also work for "timestamp": "2019-07-02T13:00:34+02:00" and "timestamp": "2019-07-02T13:00:34.090909090+02:00". I found this answer showing how to parse such strings with a DateTimeFormatter, but as far as I can tell, @JsonFormat only takes a SimpleDateFormat string, which do not have support for variable amounts of second decimals.

Removing the pattern-property all together, so the annotation becomes

@JsonFormat(shape = JsonFormat.Shape.STRING)

allows me to parse the incoming dates, but also accepts non-RFC3339 timestamps like 1990-01-01T12:53:01-0110 (missing a colon in the timezone).

Froff
  • 43
  • 1
  • 7
  • 2
    I haven't got the experience, but I would expect that if you change from the outdated `Date` to the modern `OffsetDateTime` and use jackson-modules-java8 (please search), it then will work out of the box. – Ole V.V. Jul 02 '19 at 13:29
  • 2
    FYI, that input string is actually in standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. RFC 3339 is but a self-declared “profile” of ISO 8601. Unfortunately, rather than adding value, RFC 3339 actually contradicts the original standard with needless changes. I suggest sticking with ISO 8601 and avoiding RFC 3339 entirely. The *java.time* classes support ISO 8601. – Basil Bourque Jul 02 '19 at 16:41

1 Answers1

3

Once the JavaTimeModule is registered in your ObjectMapper, simply use OffsetDateTime instead of Date. There's no need for @JsonFormat.

See the example below:

@Data
public class Foo {
    private OffsetDateTime timestamp;
}
String json =
        "{\n" +
        "  \"timestamp\": \"2019-07-02T13:00:34.090909090+02:00\"\n" +
        "}\n";

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

Foo foo = mapper.readValue(json, Foo.class);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • While this fails on special leap-second cases like `1990-12-31T23:59:60Z` (from [the RFC3339 spec](https://tools.ietf.org/html/rfc3339#section-5.8), it succeeds and fails correctly in all my other test, so I'm accepting it. Thank you! – Froff Jul 03 '19 at 07:25