Add json processor to springboot

Keywords: JSON Spring

spring supports the json parser of Jackson 2 by default. Now most people are used to the parser of fastJson. Now it's easy to say how to configure the json parser

jackson2

The configuration is as follows:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

 //JackSon configuration
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        ObjectMapper objectMapper = builder.build();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// Ignore transient decorated properties
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
        super.configureMessageConverters(converters);
    }
}

You can use @ jsonformat (shape = jsonformat. Shape. String, pattern = "yyyy MM DD HH: mm: SS", locale = "zh", timezone = "GMT + 8") to format the output of Date data The default date is 0 time zone. 8 a.m. will become 0 a.m The @ Transient annotation is supported, and the fields decorated by the annotation will not be output

fastjson

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

   @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
}

This configuration supports versions after 1.2.10. If you have any problems, please upgrade fastjson You can use @ JSONField to configure serialized properties

@JSONField(format = "yyyy-MM-dd HH:mm:ss")

The @ Transient annotation is supported, and the fields decorated by the annotation will not be output

Posted by jesse_james on Fri, 24 Apr 2020 09:24:04 -0700