Hello, in this chapter we add a custom message converter. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

One: What does a message converter do?

I don’t know if you’ve ever seen a situation where a background interface returns an instance, and when you want to use the value of an attribute, you have to check whether the value is null; Interface returns a bunch of null attributes, etc

Ok, message converter can help you solve this problem

Add fastJSON dependencies

Open pem.xml, find the
tag, and add the FastJSON dependency to the tag

Alibaba </groupId> <artifactId>fastjson</artifactId> <version>1.2.22</version> </dependency>Copy the code

Then right-click Maven→Reimport to download the dependency

Three: Create a configuration file

Create WebConfigurer in the folder Configurer

package com.example.demo.core.configurer; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * @author * @description: * @time 2018/4/19 10:42 */ @Configuration public class WebConfigurer extends WebMvcConfigurationSupport { /** * Modify the custom message converter * @ param converters * / @ Override public void configureMessageConverters (List < HttpMessageConverter <? >> converters) { FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4(); converter.setSupportedMediaTypes(getSupportedMediaTypes()); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures( // String null ->""SerializerFeature.WriteNullStringAsEmpty, // Number null -> 0 SerializerFeature.WriteNullNumberAsZero, / / prohibit circular reference SerializerFeature. DisableCircularReferenceDetect); converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(converter);
    }

    private List<MediaType> getSupportedMediaTypes() {
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        returnsupportedMediaTypes; }}Copy the code

Among them

config.setSerializerFeatures()Copy the code

You can add multiple configurations in this method. The following lists some common configurations. For more configurations, please search for them

If the WriteNullListAsEmpty: List field is null, the output is [], not null. WriteNullStringAsEmpty: character type field if null, the output is""Rather than null DisableCircularReferenceDetect: to eliminate the problem of cyclic references to the same object, by defaultfalseWriteNullBooleanAsFalse: Boolean If the field is null, the output isfalseWriteMapNullValue: Specifies whether to output a field with a null value. The default value is nullfalseCopy the code

Four: add test data to the database

INSERT INTO `user_info` VALUES ('1'.'1');
INSERT INTO `user_info` VALUES ('2', null);Copy the code

5: test

The query condition ID is 2

If no converter is configured, the query result is

{
    "code": 200,
    "msg": "success"."data": {
        "id": 2."userName": null
    }
}Copy the code

After the converter is configured, the query result is

{
    "code": 200,
    "data": {
        "id": 2."userName": ""// This is already changed to""Instead of null},"msg": "success"
}Copy the code

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

Springboot to add custom message converter has been completed, the subsequent functions will be updated, you can contact me at [email protected]. Ask for directions from various gods, thank you.