Jackson object mapper includes escape sequence in responses

13,298

Solution 1

The problem is the line below.

mapper.writerWithDefaultPrettyPrinter().writeValue(writer,train);  

Try replacing it with

mapper.writeValue(writer,train);

Why do you create a new object mapper when you are configuring, MappingJackson2HttpMessageConverter?
You can autowire the object mapper or return the actual object and let spring convert it to json

Solution 2

That's a "simple" double encoding issue i believe. You set a string in the response entity which is again writen as a json response.

If you want to rely on the spring view rendering (mappingjackson2httpmessageconverter) you have to create a response entity for "Train". (Or return a train instance directly from your controller method)

Or you use the way you implemented it and you have to ensure that rendering a string for a json response will not use the jackson message converter, but is left untouched by spring.

Share:
13,298
Rithik_Star
Author by

Rithik_Star

Updated on August 21, 2022

Comments

  • Rithik_Star
    Rithik_Star over 1 year

    When I use object mapper, it inluces \r\n in the responses.Help me how to resolve it. I am having train POJO and it has String name and String Value. I set name as "Sydney" and Value as "SYD".It reruns

    {\ \ \"name \" : \"Sydney\",\ \ \"Value \" : \"SYD\",\ \ \"isEnable\" : false,\ \ \"isCurrent\" : false\ \ }"
    

    raw value in browser

    "{\r\n  \"name\" : \"Sydney\",\r\n  \"name\" : \"SYD\",\r\n  \"isEnable\" : false,\r\n  \"isCurrent\" : false\r\n}"
    

    below is my code Train

    public class Train {
    
        public Train() {
        }
    
    
        private String name;
        private String value; 
        private String Code;
        private String countryName;
        private String state;
        private String stateName;
        private boolean isEnable;
        private boolean isCurrent;
    
        //*getters and setters/*/
        }
    

    Controller calss

    public ResponseEntity<String> getDetails(   )       
                throws IOException {
            ResponseEntity<String> responseEntity = null;
    
            try(StringWriter writer = new StringWriter()) {
                ObjectMapper mapper = new ObjectMapper();           
                Train train = new Train();
              // set name and value to the train object//
    
                 if(train != null)
                 {
                    mapper.setSerializationInclusion(Inclusion.NON_NULL);
                    mapper.setSerializationInclusion(Inclusion.NON_EMPTY);
    
                 mapper.writerWithDefaultPrettyPrinter().writeValue(writer,
                        train);         
                responseEntity = new ResponseEntity<>(writer.toString(),
                        HttpStatus.OK);
                 }
                 }
              catch()
                 {}              
                 return responseEntity;
                 }
    

    Configuration:

    @Override
        public void configureMessageConverters(
                List<HttpMessageConverter<?>> converters) {
            converters.add(extendedJsonConvertor());
            super.configureMessageConverters(converters);
        }
    
        @Bean
        public MappingJackson2HttpMessageConverter extendedJsonConvertor() {
            MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    
            mappingJackson2HttpMessageConverter
                    .setObjectMapper(getNullAndEmptyFilteredObjectMapper());
            return mappingJackson2HttpMessageConverter;
        }
    
        @Bean
        public ObjectMapper getNullAndEmptyFilteredObjectMapper() {
            ObjectMapper objectMapper = new ObjectMapper();     
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            objectMapper.configure(
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return objectMapper;
        }
    

    When I debug the above code I came to know mapper include those \r\n in the response.Help me how to remove those slashes.

  • Haim Raman
    Haim Raman over 9 years
    make sure you are using MappingJackson2HttpMessageConverter. what is your spring version
  • Haim Raman
    Haim Raman over 9 years
    make sure you are actually using this code (place a breakpoint). maybe it's overriding in some place. Try forcing the disable mapper.disable(SerializationFeature.INDENT_OUTPUT);
  • Rithik_Star
    Rithik_Star over 9 years
    @Hamin I defined mapper in configuration class but I am creating instance of mapper through ObjectMapper mapper = new ObjectMapper(); .Will it cuase this issue
  • Rithik_Star
    Rithik_Star over 9 years
    I tried autowiring the object mapper but it return context initialization failed .bcas I am calling those object mapper in configure message converters in configuration class so I am unable to autowired the mapper
  • Rithik_Star
    Rithik_Star over 9 years