When using Spring MVC for REST, how do you enable Jackson to pretty-print rendered JSON?

后端 未结 10 553
遥遥无期
遥遥无期 2020-12-04 14:25

While developing REST services using Spring MVC, I would like render JSON \'pretty printed\' in development but normal (reduced whitespace) in production.

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 14:51

    Jackson 2 has a nicer API, agreed, but it won't resolve this problem in a Spring MVC environment given Spring MVC uses ObjectMapper#writeValue(JsonGenerator, Object) to write objects out as JSON. This writeValue variant does not apply ObjectMapper serialization features such as INDENT_OUTPUT in either Jackson 1.x or 2.0.

    I do think this is somewhat confusing. Since we use the ObjectMapper to construct JsonGenerators, I'd expect returned generators to be initialized based on configured ObjectMapper settings. I reported this as a issue against Jackson 2.0 here: https://github.com/FasterXML/jackson-databind/issues/12.

    Les's suggestion of calling JsonGenerator#useDefaultPrettyPrinter based on the value of a prettyPrint flag is about the best we can do at the moment. I've gone ahead and created a Jackson2 HttpMessageConverter that does this based on the enabled status of the INDENT_OUTPUT SerializationFeature: https://gist.github.com/2423129.

提交回复
热议问题