spring中配置fastjson作为默认的json实现,替换默认的jackson。
1、WebConfig配置类:
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* 配置全站允许CORS跨域访问
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") //允许的来源域 如http://www.demo.com
.allowedMethods("GET", "POST","PUT","DELETE","PUT")
.allowCredentials(false).maxAge(3600);
}
/**
* 替换springmvc中jackson为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.WriteMapNullValue,
// SerializerFeature.WriteNullNumberAsZero,
// SerializerFeature.WriteNullStringAsEmpty
// );
// fastConverter.setFastJsonConfig(fastJsonConfig);
// 处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
//处理字符串, 避免直接返回字符串的时候被添加了引号
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
converters.add(stringConverter);
converters.add(fastConverter);
}
}
2、java bean中自定义Json序列化输出字段名称
使用fastjson中提供的@JSONField注解,设置bean中字段的json输出名称,如:
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class UserInfo implements Serializable {
private static final long serialVersionUID = 7104959704215437045L;
@JSONField(name = "FullName")
private String FullName; //姓名
@JSONField(name = "UserPhone")
private String UserPhone; //手机号
//...
}


阅读排行


Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1