全局替换双斜杠(转义+反斜杠)为单斜杠

简介: 全局替换双斜杠(转义+反斜杠)为单斜杠

今天经IOS开发小哥哥反馈,让我将全局返回的双斜杠\\替换为单斜杠\

于是有了下面这段代码:

@Override
protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    MediaType contentType = outputMessage.getHeaders().getContentType();
    JsonEncoding encoding = getJsonEncoding(contentType);

    Class<?> clazz = (object instanceof MappingJacksonValue mappingJacksonValue ?
            mappingJacksonValue.getValue().getClass() : object.getClass());
    ObjectMapper objectMapper = ReflectUtil.invoke(this, "selectObjectMapper", clazz, contentType);
    Assert.state(objectMapper != null, () -> "No ObjectMapper for " + clazz.getName());

    OutputStream outputStream = StreamUtils.nonClosing(outputMessage.getBody());
    try (JsonGenerator generator = objectMapper.getFactory().createGenerator(outputStream, encoding)) {
        writePrefix(generator, object);
        String json = objectMapper.writeValueAsString(object);
        // 替换双斜杠为单斜杠
        json = json.replace("\\\\", "\\");
        generator.writeRaw(json);
        writeSuffix(generator, object);
        generator.flush();
    } catch (InvalidDefinitionException ex) {
        throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getOriginalMessage(), ex);
    }
}

是在自定义的MappingJackson2HttpMessageConverter里做的

import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;

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

@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) // 仅当为WebMvc应用时激活
public class Jackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter implements InitializingBean {

    @Resource
    private JacksonObjectMapper objectMapper;

    @Override
    public boolean canRead(@Nullable MediaType mediaType) {
        return super.canRead(mediaType) || "text".equals(mediaType.getType());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setObjectMapper(objectMapper);
    }

    @Override
    protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        MediaType contentType = outputMessage.getHeaders().getContentType();
        JsonEncoding encoding = getJsonEncoding(contentType);

        Class<?> clazz = (object instanceof MappingJacksonValue mappingJacksonValue ?
                mappingJacksonValue.getValue().getClass() : object.getClass());
        ObjectMapper objectMapper = ReflectUtil.invoke(this, "selectObjectMapper", clazz, contentType);
        Assert.state(objectMapper != null, () -> "No ObjectMapper for " + clazz.getName());

        OutputStream outputStream = StreamUtils.nonClosing(outputMessage.getBody());
        try (JsonGenerator generator = objectMapper.getFactory().createGenerator(outputStream, encoding)) {
            writePrefix(generator, object);
            String json = objectMapper.writeValueAsString(object);
            // 替换双斜杠为单斜杠
            json = json.replace("\\\\", "\\");
            generator.writeRaw(json);
            writeSuffix(generator, object);
            generator.flush();
        } catch (InvalidDefinitionException ex) {
            throw new HttpMessageConversionException("Type definition error: " + ex.getType(), ex);
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getOriginalMessage(), ex);
        }
    }

}
相关文章
如何去掉字符串开头,结尾或者中间的空格及其他不想要的字符
去掉文本字符串开头,结尾或者中间不想要的字符,比如空白。
|
6月前
|
C语言 C++
每天一道C语言编程:(去掉:双斜杠注释,去掉空格)
每天一道C语言编程:(去掉:双斜杠注释,去掉空格)
32 0
|
6月前
|
移动开发
基于Notepad++ 快速替换 换行符 为 逗号
【5月更文挑战第5天】基于Notepad++ 快速替换 换行符 为 逗号
|
6月前
|
Shell Perl
用sed如果原字符串或新字符串中包含特殊字符(如正斜杠/或其他特殊字符),需要用\进行转义
用sed如果原字符串或新字符串中包含特殊字符(如正斜杠/或其他特殊字符),需要用\进行转义
675 7
|
Unix Linux Windows
路径中的正斜杠/ 与反斜杠\
路径中的正斜杠/ 与反斜杠\
66 0
|
监控 Python
一日一技:批量转义正则表达式中的特殊符号
一日一技:批量转义正则表达式中的特殊符号
98 0
|
机器学习/深度学习 Shell C++
正则表达式普通字符、非打印字符、特殊字符、限定符的应用、定位符、元字符(规则,匹配,和实际使用)与运算符优先级
正则表达式普通字符、非打印字符、特殊字符、限定符的应用、定位符、元字符(规则,匹配,和实际使用)与运算符优先级
272 0
|
Shell Linux Perl
Shell的正则表达式入门、常规匹配、特殊字符:^、$、.、*、字符区间(中括号):[ ]、特殊字符:\、匹配手机号
Shell的正则表达式入门、常规匹配、特殊字符:^、$、.、*、字符区间(中括号):[ ]、特殊字符:\、匹配手机号
Shell的正则表达式入门、常规匹配、特殊字符:^、$、.、*、字符区间(中括号):[ ]、特殊字符:\、匹配手机号
用#替换字符
给定一个由大小写字母构成的字符串。 把该字符串中特定的字符全部用字符 # 替换。
119 0
|
JavaScript
js:RegExp正则表达式匹配任意字符(包括换行符)
js:RegExp正则表达式匹配任意字符(包括换行符)
133 0