简体   繁体   中英

Jackson not displaying in Pretty Print format

I am using below code to convert my Java object into 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

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

[ {\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. Please note that since the object I am trying to convert to json is dynamic there is no option of using annotations on 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 :

@RequestMapping(value = "/{xxx}/{xxx}/{xxx}/", method = RequestMethod.GET, produces = "text/plain")

So now its like my response is a plain text representation of JSON.

I had tried using application/json when I used Spring Web/MVC. But somehow it seems application/json is not working for Spring Boot.

If you just want the json to print pretty in the browser theres plenty of plugins that do that for you. https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM