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

后端 未结 10 510
遥遥无期
遥遥无期 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:56

    Might I suggest this approach, it is valid with Spring 4.0.x and possibly older versions.

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    import java.util.List;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    @EnableWebMvc    
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    
        @Bean
        public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
            MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
            mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper());
            return mappingJackson2HttpMessageConverter;
        }
    
        @Bean
        public ObjectMapper objectMapper() {
            ObjectMapper objMapper = new ObjectMapper();
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            return objMapper;
        }
    
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            super.configureMessageConverters(converters);        
            converters.add(mappingJackson2HttpMessageConverter());
        }
    
    }
    

    Thanks to Willie Wheeler for the solution: Willie Wheeler's Spring blog

    0 讨论(0)
  • 2020-12-04 15:02

    When you are using Jackson 2.0.0, you can do it in a way Les wanted to. I currently use RC3 and the configuration seems to be working as expected.

    ObjectMapper jacksonMapper = new ObjectMapper();
    jacksonMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    

    translates

    {"foo":"foo","bar":{"field1":"field1","field2":"field2"}}
    

    into

    {
      "foo" : "foo",
      "bar" : {
        "field1" : "field1",
        "field2" : "field2"
      }
    }
    
    0 讨论(0)
  • 2020-12-04 15:02

    Pretty print will be enable by adding and configure the MappingJackson2HttpMessageConverter converter. Disable prettyprint within production environment.

    Message converter configuration

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean id="jacksonHttpMessageConverter"
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="${json.prettyPrint}" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    
    0 讨论(0)
  • 2020-12-04 15:05

    How do I make Jackson pretty-print the JSON content it generates?

    Here's a simple example:

    Original JSON Input:

    {"one":"AAA","two":["BBB","CCC"],"three":{"four":"DDD","five":["EEE","FFF"]}}
    

    Foo.java:

    import java.io.FileReader;
    
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.map.ObjectWriter;
    
    public class Foo
    {
      public static void main(String[] args) throws Exception
      {
        ObjectMapper mapper = new ObjectMapper();
        MyClass myObject = mapper.readValue(new FileReader("input.json"), MyClass.class);
        // this is Jackson 1.x API only: 
        ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
        // ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above: 
        // ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
        System.out.println(writer.writeValueAsString(myObject));
      }
    }
    
    class MyClass
    {
      String one;
      String[] two;
      MyOtherClass three;
    
      public String getOne() {return one;}
      void setOne(String one) {this.one = one;}
      public String[] getTwo() {return two;}
      void setTwo(String[] two) {this.two = two;}
      public MyOtherClass getThree() {return three;}
      void setThree(MyOtherClass three) {this.three = three;}
    }
    
    class MyOtherClass
    {
      String four;
      String[] five;
    
      public String getFour() {return four;}
      void setFour(String four) {this.four = four;}
      public String[] getFive() {return five;}
      void setFive(String[] five) {this.five = five;}
    }
    

    Output:

    {
      "one" : "AAA",
      "two" : [ "BBB", "CCC" ],
      "three" : {
        "four" : "DDD",
        "five" : [ "EEE", "FFF" ]
      }
    }
    

    If this approach doesn't exactly fit your needs, if you search the API docs v1.8.1 for "pretty", it'll turn up the relevant components available. If you use API version 2.x then look instead at the newer API 2.1.0 docs.

    0 讨论(0)
提交回复
热议问题