【问题标题】:How to escape slashes in Gson如何在 Gson 中逃脱斜线
【发布时间】:2015-04-20 02:24:41
【问题描述】:

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

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

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

【问题讨论】:

  • String someString = "/"; someString = someString.replace("/", "\\/"); System.out.println(someString); 输出:>> \/
  • @Selim 没有帮助。检查我的编辑
  • @stoefln Selim 的意思是:在序列化之后(即在 JSON 字符串上)进行替换,而不是之前。
  • 自定义 TypeAdapter 可能会有所帮助:google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/…
  • @stoefln 添加了一个可能满足您需求的答案 :) 如果您需要额外支持,请告诉我。

标签: java json gson


【解决方案1】:

答案:自定义序列化程序

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

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"

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

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

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

可下载和可执行的示例

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

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


另请参阅

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 2017-10-31
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多