SpringMVC返回不带引号的字符串方案汇总

SpringMVC返回不带引号的字符串方案汇总

问题

项目使用springboot开发的,大部分出参为json,使用的fastJson。

现在有的接口需要返回一个success字符串,发现返回结果为“success”,多带了双引号。这是因为fastJson对出参做了处理。

方案一:fastJson添加string类型的解析器(推荐)

创建一个配置类

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter(){
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    @Bean
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setFeatures(SerializerFeature.DisableCircularReferenceDetect);
        converter.setCharset(StandardCharsets.UTF_8);
        return converter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //添加字符转解析器
        converters.add(stringHttpMessageConverter());
        //添加json解析器
        converters.add(fastJsonHttpMessageConverter());
    }

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

方案二:修改springMVC配置文件(springMVC)

网上通用的办法是在springMVC配置文件spring-servlet.xml中加入如下配置项:

<mvc:annotation-driven>
        <mvc:message-converters>  
        	
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<constructor-arg value="UTF-8" />
				  
		        <property name="supportedMediaTypes">  
		            <list>  
		                <value>text/plain;charset=UTF-8value>  
		            list>  
		        property>
			bean>
		      
		    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        mvc:message-converters> 
mvc:annotation-driven>

也可以在applicationContext-velocity.xml,配置JSON返回模板时直接配置进去


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<bean id="mappingJackson2HttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/json;charset=UTF-8value>
				
			list>
		property>
	bean>
	<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" />
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJackson2HttpMessageConverter" />
				<ref bean="stringHttpMessageConverter" />
			list>
		property>
	bean>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  
	       <property name="prefix" value="/" />
	       <property name="suffix" value=".html" />
	       <property name="contentType" value="text/html;charset=UTF-8" />
	       <property name="requestContextAttribute" value="request"/>
	       
	       <property name="dateToolAttribute" value="dateTool" />
	       <property name="numberToolAttribute" value="numberTool" />
	       <property name="exposeRequestAttributes" value="true" />
	       <property name="exposeSessionAttributes" value="true" />
   bean>
beans>

方案三:重写Jackson消息转换器的writeInternal方法(springMVC)

创建一个MappingJackson2HttpMessageConverter的工厂类

public class MappingJackson2HttpMessageConverterFactory {
    private static final Logger logger = getLogger(MappingJackson2HttpMessageConverterFactory.class);
    public MappingJackson2HttpMessageConverter init() {
        return new MappingJackson2HttpMessageConverter(){
            /**
             * 重写Jackson消息转换器的writeInternal方法
             * SpringMVC选定了具体的消息转换类型后,会调用具体类型的write方法,将Java对象转换后写入返回内容
             */
            @Override
            protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
                if (object instanceof String){
                    logger.info("在MyResponseBodyAdvice进行转换时返回值变成String了,不能用原来选定消息转换器进行转换,直接使用StringHttpMessageConverter转换");
                    //StringHttpMessageConverter中就是用以下代码写的
                    Charset charset = this.getContentTypeCharset(outputMessage.getHeaders().getContentType());
                    StreamUtils.copy((String)object, charset, outputMessage.getBody());
                }else{
                    logger.info("返回值不是String类型,还是使用之前选择的转换器进行消息转换");
                    super.writeInternal(object, type, outputMessage);
                }
            }
            private Charset getContentTypeCharset(MediaType contentType) {
                return contentType != null && contentType.getCharset() != null?contentType.getCharset():this.getDefaultCharset();
            }
        };
    }
}

在spring mvc的配置文件中添加如下配置

<mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>image/jpegvalue>
                        <value>image/pngvalue>
                        <value>image/gifvalue>
                    list>
                property>
            bean>
            <bean  factory-bean="mappingJackson2HttpMessageConverterFactory" factory-method="init"
                   class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
 
    <bean id="mappingJackson2HttpMessageConverterFactory" class = "com.common.MappingJackson2HttpMessageConverterFactory" />

方案四:response.getWriter().write()写到界面

 @PostMapping("/test")
    public void test(@RequestBody Req req, HttpServletResponse response) throw Exception{
            res = service.test(req);
            response.getWriter().write(res);
            response.getWriter().flush();
            response.getWriter().close();
    }

方案五:重写json的MessageCoverter

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        return new StringHttpMessageConverter();
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(stringHttpMessageConverter());
    }
}
@Configuration
@Slf4j
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 使用fastjson转换器
     * 
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
            SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.DisableCircularReferenceDetect);
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        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);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }

}

参考:

SpringMVC返回字符串去掉引号:https://blog.csdn.net/u013268066/article/details/51603604

Spring MVC中对response数据去除字符串的双引号:https://blog.csdn.net/qq_26472621/article/details/102678232

解决springMvc返回字符串有双引号:https://blog.csdn.net/weixin_45359027/article/details/97131384

springmvc返回不带引号的字符串:https://blog.csdn.net/weixin_34390996/article/details/92531295

SpringBoot返回字符串,多双引号:https://blog.csdn.net/baidu_27055141/article/details/91544019

你可能感兴趣的:(springboot,java,spring,boot,spring)