I'm using this method to convert any object to a json string:
private String objectToJson(Object object) throws IOException {
// write JSON
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());
mapper.writeValue(jsonGenerator, object);
return writer.toString();
}
When the object being printed contains fields that are java.util.Date or jodatime's DateTime, the printed value is the number of milliseconds since the epoch. I would like, instead, to pretty-print them in a standard "HH:MM:SS" notation. How should I go about doing this?
We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.
It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).
This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);
public interface JsonGenerator extends Flushable, Closeable. Writes JSON data to an output source in a streaming way. The class Json contains methods to create generators for character or output streams ( Writer and OutputStream ).
This was already mentioned in FAQ first answer points to, but just in case: you can choose between numeric and textual representation (numeric being used by default since it is much faster) by using this feature:
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
doing this will use the default date format, which you can then redefine as mentioned (with setDateFormat).
Also: you can simplify you code like so:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
return mapper.writeValueAsString(object);
instead of using StringWriter and JsonGenerator explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With