Pergunta

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?

Foi útil?

Solução

Because the epoch timestamp (number of milliseconds since January 1st, 1970, UTC) is the most efficient and accurate representation of the time, nearly all date and time related objects are serialized to it. You can of course overwrite it and if you want to use the format mentioned in the question, you'd need to add the following to your code:

DateFormat myDateFormat = new SimpleDateFormat("hh:mm:ss");
objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
objectMapper.getDeserializationConfig().setDateFormat(myDateFormat); 

For more information regarding dates and times in the Jackson JSON-processor see the following link: http://wiki.fasterxml.com/JacksonFAQDateHandling

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top