How to return JSON and XML in springboot

The first time I wrote a blog in CSDN, right should be used to record my learning experience.

I've always wanted to find out how to implement it in springboot, that is, to support JSON data return format and XML at the same time. Today, I finally implemented it and measured it myself, so it's quality assurance, ha ha.

So let's start with the popularization of basic knowledge.

Students who have used Springboot know that there are three ways to add a converter to Springboot. The code and instructions are as follows:

// The first way to add converter is simple code and recommended way
    // In this way, springboot will put our custom converter at the highest priority in the order (the header of the List)
    // That is, when multiple converter s meet the rules of Accpet/ContentType/MediaType, our
    @Bean
    public JavaSerializationConverter javaSerializationConverter() {
        return new JavaSerializationConverter();
    }

    // The second way to add converter
    // Usually, when there is only one custom WebMvcConfigurerAdapter, the converter(s) added in this method will be placed in the highest priority (the header of the List) in turn
    // Although the code of the first method is executed first, the bean is added later than this method, so the priority of method 2 is higher than that of method 1
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // The add method can specify the order. When there are multiple custom webmvcconfigureradapters, the order between them can be changed
        // But it's all in front of spring MVC's built-in converter
        converters.add(new JavaSerializationConverter());
    }

    // The third way to add converter
    // The configureMessageConverters method in the same WebMvcConfigurerAdapter executes before the extendMessageConverters method
    // It can be understood that it is the last one of the three methods, but here you can adjust the priority by specifying the order of add, or you can use remove/clear to delete the converter, which is powerful
    // Use converters.add(xxx) to place it at the lowest priority (at the end of the List)
    // Use converters.add(0,xxx) to put it at the highest priority (the head of the List)
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new JavaSerializationConverter());
    }

Here we add the Fastjson converter in the third way

@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport
{

 @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter()
    {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //by default, fastjson does not output the null value unless SerializerFeature.WriteMapNullValue is added
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //Dealing with the problem of Chinese random code
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        return fastJsonHttpMessageConverter;
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0,fastJsonHttpMessageConverter());
    }
}

In this way, we have the JSON converter in our project, which depends on

 

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.55</version>
        </dependency>

Here is the key. How to support XML at the same time? First, add a dependency

<dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-xml-provider</artifactId>
        </dependency>

At this time, our project can support data return in XML or JSON at the same time, and only need to add when the front-end calls

Accept: application/xml or Accept: application/json
If you don't want to specify Accept, you can directly specify whether to return xml or JSON through the API URL by referring to the following methods

First, configure WebMvcConfigurationSupport

@Configuration
public class FastJsonConfiguration extends WebMvcConfigurationSupport
{
@Override
    protected void configurePathMatch(PathMatchConfigurer configurer) {
        /**
         *  setUseSuffixPatternMatch : Set whether the suffix pattern matches, such as whether / user matches / user. *, the default value is true;
         *  setUseTrailingSlashMatch : Set whether to automatically match the suffix path pattern, for example, "/ user" matches "/ user /", and the default value is "true"
         */
                configurer.setUseSuffixPatternMatch(true)
                .setUseTrailingSlashMatch(true);
    }
}

Define another method to show how to use

 @ApiOperation(value = "get the user info by soeid", notes = "fetch the data from user table with the passed soeid")
    @ApiImplicitParam(paramType = "path", name = "soeid", value = "need to pass the soeid", required = true, dataType = "String")
    @GetMapping(value="/getUserInfo/{soeid}")
    public  BaseResult<Userqt> getUserInfo(@PathVariable(value = "soeid") String soeid)
    {
//        logger.info("call the method to get the user info by SOEID");
        Userqt user = userqtMapper.selectUserBySOEID(soeid);
        return ResultUtil.success(user);
    }

http://localhost:8010/getUserInfo/aa.json Return to JSON

http://localhost:8010/getUserInfo/aa . xml returns xml

If you have any questions, welcome to discuss^_^

Published 1 original article, praised 0, visited 8
Private letter follow

Tags: xml JSON SpringBoot Spring

Posted on Thu, 30 Jan 2020 00:32:13 -0800 by linux_pickle