fastjson
fastjson copied to clipboard
转换反斜杠报错
将fastjson配置到springmvc的转换器中时,如果前端输入了反斜杠,解析时会报出一个错误,JSON parse error: unclosed string : \u001a; nested exception is com.alibaba.fastjson.JSONException: unclosed string : \u001a ,需要做什么特殊配置吗,我已经添加了prettyFormat和WriteSlashAsSpecial两个配置.
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// Create Fastjson HTTP message converter
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// Configure Fastjson
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
// 设置美化输出
SerializerFeature.PrettyFormat,
// 将反斜杠写成特殊字符转义
SerializerFeature.WriteSlashAsSpecial
);
converter.setFastJsonConfig(config);
// Add supported media types
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
converter.setSupportedMediaTypes(supportedMediaTypes);
// Add the converter to the converters list
converters.add(converter);
}
}