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

2024-01-28 10:21:03 浏览数 (1)

心气和平,玉体安宁。——佚名

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

于是有了下面这段代码:

代码语言:javascript复制
@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里做的

代码语言:javascript复制
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);
        }
    }

}

0 人点赞