[英]Jackson not displaying in Pretty Print format
I am using below code to convert my Java object into JSON : 我正在使用下面的代码将Java对象转换为JSON:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new SnapshotModule()).setTimeZone(timeZone)
.enable(SerializationFeature.INDENT_OUTPUT)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)
.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
String respJson = mapper .writerWithDefaultPrettyPrinter().writeValueAsString(obj)
This is returned to the Spring Controller RequestMapping which is annotated like below 这将返回到Spring Controller RequestMapping,如下所示
@RequestMapping(value = "/{xxx}/{xxx}/{xxx}/", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
When I print this response in logger I can see well prettyprint JSON format along with indentations. 当我在记录器中打印此响应时,我可以看到很好的prettyprint JSON格式以及缩进。 However, when I hit the Rest URL in browser to see the response is seen with \\r\\n characters instead of actual new lines with indentation like this -
但是,当我在浏览器中点击“ REST URL”以查看响应时,显示的是\\ r \\ n个字符,而不是像这样的带有缩进的实际新行-
[ {\r\n \"XXX\" : {\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : { },\r\n \"XXX\" : true\r\n },\r\n \"XXX\" : {\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\"\r\n },\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\",\r\n \"XXX\" : \"XXX\"\r\n} ]"
Can someone please help on what is wrong with my approach. 有人可以帮我解决我的方法的问题吗。 I even tried using gson library and result is same.
我什至尝试使用gson库,结果是相同的。 Please note that since the object I am trying to convert to json is dynamic there is no option of using annotations on pojo.
请注意,由于我尝试转换为json的对象是动态的,因此无法在pojo上使用注释。
[SOLUTION] - [解决方案]-
I could figure out a solution for this which looks to be wierd but it worked out. 我可以想出一个解决方案,虽然看起来很麻烦,但还是可以解决的。
I modified the Spring RequestMapping as below : 我修改了Spring RequestMapping如下:
@RequestMapping(value = "/{xxx}/{xxx}/{xxx}/", method = RequestMethod.GET, produces = "text/plain")
So now its like my response is a plain text representation of JSON. 所以现在我的响应就像是JSON的纯文本表示形式。
I had tried using application/json when I used Spring Web/MVC. 当我使用Spring Web / MVC时,我曾尝试使用application / json。 But somehow it seems application/json is not working for Spring Boot.
但是以某种方式看来application / json对于Spring Boot不起作用。
If you just want the json to print pretty in the browser theres plenty of plugins that do that for you. 如果您只是想让json在浏览器中漂亮地打印,那么有很多插件可以为您完成此任务。 https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en
https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=zh-CN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.