springmvc+swagger2整合

整合的过程中遇到了一些问题,特此记录。

问题一:springmvc中使用fastJsonHttpMessageConverter导致swagger2 解析json失败若果换成mappingJackson2HttpMessageConverter就没事儿了,但是感觉fastjson性能更好一些,所以就得硬着头皮解决swagger2与fastjson兼容的问题。网上有很多解决方案,无非就是说换最高版本的fastjson就好了,但是我换了最新版的fastjson还是不行,不知道为什么,所以只能按照网上说的方法,来喽,大概意思就是自定义一个fastjson转换器。上代码

FastJsonHttpMessageConverterEx

package core.swagger;

import springfox.documentation.spring.web.json.Json;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {

    public FastJsonHttpMessageConverterEx() {
        super();
        this.getFastJsonConfig().getSerializeConfig().put(Json.class, SwaggerJsonSerializer.instance);
    }

}
SwaggerJsonSerializer

package core.swagger;

import java.io.IOException;
import java.lang.reflect.Type;

import springfox.documentation.spring.web.json.Json;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class SwaggerJsonSerializer implements ObjectSerializer, ObjectDeserializer {

    public final static SwaggerJsonSerializer instance = new SwaggerJsonSerializer();

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.getWriter();
        Json json = (Json) object;
        out.write(json.value());
    }

    @Override
    public  T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        return null;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }

}
springmvc配置文件


		
			
				
					
						text/plain;charset=UTF-8
						text/html;charset=UTF-8
						application/json;charset=UTF-8
					
				
				
					
						DisableCircularReferenceDetect
						WriteMapNullValue
						WriteNullNumberAsZero
						WriteNullStringAsEmpty
						WriteNullListAsEmpty
						WriteNullBooleanAsFalse
					
				
			
		
	

成功解决问题

问题二:用springmvc写了一个登录拦截器,swagger2的所有请求都拦截了,由于swagger2是引入的jar包,所以跟了下代码,配置了一下拦截器


		
			
			
			
			
			
				
					
						/tbuser/noUser
						/tbuser/login
						/swagger-ui.html
					
				
			
		
	
成功解决问题




你可能感兴趣的:(springmvc,swagger2)