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

前端 未结 2 862
慢半拍i
慢半拍i 2021-02-15 00:03

I\'m using this method to convert any object to a json string:

private String objectToJson(Object object) throws IOException {
        // write JSON
        Stri         


        
2条回答
  •  礼貌的吻别
    2021-02-15 00:34

    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.

提交回复
热议问题