@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
接口java
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())); } }
fastjson已經內置了一個ResponseBodyAdvice
接口的實現JSONPResponseBodyAdvice
咱們只須要配置這個Bean就好了json
@Configuration @EnableWebMvc public class WebMvcConfigurer extends WebMvcConfigurerAdapter { /** * use {@link ResponseJSONP} * controller return jsonp data */ @Bean public ResponseBodyAdvice fastJsonpResponseBodyAdvice() { return new JSONPResponseBodyAdvice(); } }