@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
/**
* fastjson configuration
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
config.setSerializeFilters((ValueFilter) (object, name, value) -> {
// 针对map类型value为null时输出""
if (Objects.isNull(value)) {
return "";
}
// 数字类型转字符串
if (value instanceof Number) {
return value.toString();
}
return value;
});
ArrayList<MediaType> mediaTypes = Lists.newArrayList();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypes.add(MediaType.TEXT_HTML);
mediaTypes.add(MediaType.APPLICATION_JSON);
mediaTypes.add(MediaType.TEXT_PLAIN);
converter.setSupportedMediaTypes(mediaTypes);
converter.setFastJsonConfig(config);
// 自定义序列化
config.getSerializeConfig().put(Response.class, new ResponseSerializer(config));
converters.add(converter);
}
}
自定义序列化实现ObjectSerializer
接口
public static class ResponseSerializer implements ObjectSerializer {
private final FastJsonConfig fastJsonConfig;
public ResponseSerializer(FastJsonConfig fastJsonConfig) {
this.fastJsonConfig = fastJsonConfig;
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
SerializeWriter out = serializer.getWriter();
Response response = (Response) object;
out.write(JSON.toJSONString(response.body, fastJsonConfig.getSerializeConfig(), fastJsonConfig.getSerializeFilters(), fastJsonConfig.getSerializerFeatures()));
}
}
jsonp注解支持
fastjson已经内置了一个ResponseBodyAdvice
接口的实现JSONPResponseBodyAdvice
我们只需要配置这个Bean就行了
@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
/**
* use {@link ResponseJSONP}
* controller return jsonp data
*/
@Bean
public ResponseBodyAdvice fastJsonpResponseBodyAdvice() {
return new JSONPResponseBodyAdvice();
}
}
来源:oschina
链接:https://my.oschina.net/u/4411698/blog/3682953