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-8</value>  
		            </list>  
		        </property>
			</bean>
		    <!-- 其他处理 -->  
		    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        </mvc:message-converters> 
</mvc:annotation-driven>

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

<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 返回JSON模版 -->
	<bean id="mappingJackson2HttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/json;charset=UTF-8</value>
				<!-- <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> -->
			</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="toolboxConfigLocation" value="/velocity-toolbox.xml" />
	        -->
	       <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/jpeg</value>
                        <value>image/png</value>
                        <value>image/gif</value>
                    </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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我认不到你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值