java - Jackson / JavaTimeModule - handle different timezone offset formats -


i'm calling api (using jersey) returns date time zone offset. data in format:

"2017-03-28t14:40:00+01:00" 

and in format (i've no control on this)

"2017-03-28t14:40:00+0100"  (where ':' in timezone offset missing). 

i want marshal these java.time.zoneddatetime objects. i'm using javatimemodule() in jersey objectmapper.

objectmapper.registermodule(new javatimemodule()); 

the question : there way make object mapper flexible enough handle time zone offset in +01:00 or +0100?

you can specify pattern optional sections (delimited []), indicate offset can have 2 different formats, , add respective field using @jsonformat annotation.

i've created test class:

public class sampletype {      @jsonformat(pattern = "yyyy-mm-dd't'hh:mm:ss[xxx][xx]")     private zoneddatetime date;      // getter , setter } 

note last part ([xxx][xx]): each pair of [] optional section, parser tries parse each one, if present. xxx offset : , xx offset without (for more details, take @ javadoc)

with this, both formats can read:

objectmapper mapper = new objectmapper(); mapper.registermodule(new javatimemodule());  // offset ":" string json = "{ \"date\": \"2017-03-28t14:40:00+01:00\" }"; sampletype value = mapper.readvalue(json, sampletype.class); system.out.println(value.getdate()); // 2017-03-28t13:40z[utc]  // offset without ":" json = "{ \"date\": \"2017-03-28t14:40:00+0100\" }"; value = mapper.readvalue(json, sampletype.class); system.out.println(value.getdate()); // 2017-03-28t13:40z[utc] 

note resulting zoneddatetime's value converted utc: 2017-03-28t13:40z[utc]

if want keep original offset, use com.fasterxml.jackson.databind.deserializationfeature class configure objectmapper:

// add preserve same offset (don't convert utc) mapper.configure(deserializationfeature.adjust_dates_to_context_time_zone, false); 

with this, offset preserved (value not converted utc), , output tests above 2017-03-28t14:40+01:00.


Comments