Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JsonGenerator pretty-print Date and DateTime values?

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?

like image 426
ripper234 Avatar asked Dec 14 '10 18:12

ripper234


People also ask

How do I change the date format in ObjectMapper?

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.

How does Jackson serialize date?

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).

How does Jackson deserialize dates from JSON?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);

What is JSON generator?

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 ).


1 Answers

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.

like image 120
StaxMan Avatar answered Sep 23 '22 03:09

StaxMan