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

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

今天经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);
        }
    }

}
相关文章
|
存储 SQL 关系型数据库
数据库的备份与恢复
数据库的备份与恢复
389 0
|
JSON JavaScript 前端开发
优化你的 HTTP 请求:JSON 与 Form-data 比较
在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:JSON与Form-data。尽管它们的终极目标一致,即数据传输的高效性和可靠性,但它们各自所具备的特点和应用情境却大相径庭,构成了数据传输的两个主要途径。
|
JSON fastjson Java
java fastJson 转JSON 两个转义
【2月更文挑战第14天】
2256 2
|
JSON 前端开发 Java
(简易详细)spring boot 使用拦截器 实现拦截前端请求并返回json到前端页面
(简易详细)spring boot 使用拦截器 实现拦截前端请求并返回json到前端页面
1899 0
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8076 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10213 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置