spring入参出参同时支持json和xml格式

Spring Boot可以通过使用Jackson库来支持同时支持JSON和XML请求和响应参数。

处理入参:

  1. 在Controller中,使用@RequestBody注解,并指定produces属性为"application/json""application/xml",以支持对应格式的请求参数。
  2. 配置HttpMessageConverter,将其注册到Spring MVC中。示例代码如下:
package com.example.demo.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
     //   ObjectMapper objectMapper = JsonMapper.builder()
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        jsonConverter.setObjectMapper(new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE));
        jsonConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, new MediaType("application", "*+json")));

        MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter();
        xmlConverter.setObjectMapper(new XmlMapper().setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE));
        xmlConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML, new MediaType("application", "*+xml")));
        converters.add(jsonConverter);
        converters.add(xmlConverter);

    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML);
    }

    @Bean
    public ContentNegotiationManager contentNegotiationManager() {
        ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean();
        factory.setDefaultContentType(MediaType.APPLICATION_JSON);
        factory.setFavorParameter(true);
        factory.setParameterName("format");
        factory.setIgnoreAcceptHeader(true);
        factory.setUseRegisteredExtensionsOnly(true);
        Map<String, MediaType> mediaTypes = new HashMap<>();
        mediaTypes.put("json", MediaType.APPLICATION_JSON);
        mediaTypes.put("xml", MediaType.APPLICATION_XML);
        factory.addMediaTypes(mediaTypes);
        return factory.getObject();
    }
}

3、编写实体类

package com.example.demo.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * TODO
 *
 * @AuThor Administrator
 * @date 2023/5/29 11:19
 * @Description
 */
@JacksonXmlRootElement(localName = "person")
public class Person {
//    解析为json或者是xml
    @JsonProperty("name")
    @JacksonXmlProperty(localName = "name")
    private String name;
    @JsonProperty("age")
    @JacksonXmlProperty(localName = "age")
    private String age;
    @JacksonXmlProperty(localName = "sex")
    @JsonProperty("sex")
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }


}

4、编写控制器

package com.example.demo.controller;

import com.example.demo.pojo.Person;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @AuThor Administrator
 * @date 2023/5/29 11:18
 * @Description
 */
@RestController
public class TestController {

/**
 * 当配置了webconfig的时候,在控制器中不需要指定类型
 * consumes = { MediaType.APPLICATION_JSON_VALUE,
            MediaType.APPLICATION_XML_VALUE },produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE}

            */
    @PostMapping(value = "/jsonAndXmlTest")
    public Person restPersion(@RequestBody Person person){
        return person;
    }
    @RequestMapping(value = "/testOther")
    public String restOther(String name){
        return name;
    }
}

以上springboot版本为2.7.x  jackson版本为2.15.1

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值