Jackson , java.time , ISO 8601 , serialize without milliseconds -
i'm using jackson 2.8 , need communicate api doesn't allow milliseconds within iso 8601 timestamps.
the expected format this: "2016-12-24t00:00:00z"
i'm using jackson's javatimemodule write_dates_as_timestamps set false.
but print milliseconds.
so tried use objectmapper.setdateformat didn't change anything.
my current workaround this:
objectmapper om = new objectmapper();  datetimeformatter dtf = new datetimeformatterbuilder()     .appendinstant(0)     .toformatter();  javatimemodule jtm = new javatimemodule(); jtm.addserializer(instant.class, new jsonserializer<instant>() {     @override     public void serialize(instant value, jsongenerator gen, serializerprovider serializers) throws ioexception, jsonprocessingexception {         gen.writestring(dtf.format(value));     } });  om.registermodule(jtm);   i'm overriding default serializer instant.class works.
is there nice way using configuration parameter solve this?
update:
just add @jsonformat annotation whith date format above instant property. it's easy.
in case have objectmapper javatimemodule next:
objectmapper mapper = new objectmapper(); mapper.registermodule(new javatimemodule());   if have class instant property, should add @jsonformat annotation , put date pattern hasn't milliseconds. next:
public static class testdate {      @jsonformat(shape = jsonformat.shape.string, pattern = "yyyy-mm-dd hh:mm:ss", timezone = "utc")     instant instant;      //getters & setters }   so if serialize object json works perfectly:
string json = mapper.writevalueasstring(testdate); system.out.println(json);    output
{"instant":"2016-11-10 06:03:06"}
old answer. don't know why doesn't work propertly:
you use jackson2objectmapperbuilder build it.
you need add dateformat want. next:
dateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");  objectmapper mapper = jackson2objectmapperbuilder             .json()                    .featurestodisable(serializationfeature.write_dates_as_timestamps)              .modules(new javatimemodule())             .dateformat(dateformat)             .build();      
Comments
Post a Comment