如何转义 Gson 中的斜杠

How to escape slashes in Gson

根据 json 规范,转义“/”是可选的。

默认情况下 Gson 不会这样做,但我正在处理一个需要转义“/”的网络服务。所以我要发送的是“somestring\/someotherstring”。关于如何实现这一点有什么想法吗?

为了让事情更清楚:如果我尝试用 Gson 反序列化“\/”,它会发送“\\/”,这是 而不是 什么我要!

答案:自定义序列化程序

您可以编写自己的自定义序列化程序 - 我创建了一个遵循您希望 / 成为 \/ 的规则但如果字符串已经转义,您希望它保留 \/ 而不是 \\/.

package com.dominikangerer.q29396608;

import java.lang.reflect.Type;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class EscapeStringSerializer implements JsonSerializer<String> {

    @Override
    public JsonElement serialize(String src, Type typeOfSrc,
            JsonSerializationContext context) {
        src = createEscapedString(src);
        return new JsonPrimitive(src);
    }

    private String createEscapedString(String src) {
        // StringBuilder for the new String
        StringBuilder builder = new StringBuilder();

        // First occurrence
        int index = src.indexOf('/');
        // lastAdded starting at position 0
        int lastAdded = 0;

        while (index >= 0) {
            // append first part without a /
            builder.append(src.substring(lastAdded, index));

            // if / doesn't have a \ directly in front - add a \
            if (index - 1 >= 0 && !src.substring(index - 1, index).equals("\")) {
                builder.append("\");
                // if we are at index 0 we also add it because - well it's the
                // first character
            } else if (index == 0) {
                builder.append("\");
            }

            // change last added to index
            lastAdded = index;
            // change index to the new occurrence of the /
            index = src.indexOf('/', index + 1);
        }

        // add the rest of the string
        builder.append(src.substring(lastAdded, src.length()));
        // return the new String
        return builder.toString();
    }
}

这将从以下字符串创建:

"12 /first /second \/third\/fourth\//fifth"`

输出:

"12 \/first \/second \/third\/fourth\/\/fifth"

注册您的自定义序列化程序

当然,您需要像这样在安装程序中将此序列化程序传递给 Gson:

Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new EscapeStringSerializer()).create();
String json = gson.toJson(yourObject);

可下载和可执行示例

你可以在我的 github Whosebug answers repo 中找到这个答案和确切的例子:

Gson CustomSerializer to escape a String in a special way by DominikAngerer


另见