根据json规范,转义“/
”是可选的。
默认情况下,Gson没有这样做,但我正在处理一个期望转义为“/
”的网络服务。所以我要发送的是“somestring\\/someotherstring
”。关于如何实现这一点的任何想法?
为了让事情更清楚:如果我尝试用Gson反序列化“\\/
”,它会发送“\\\\/
”,这是不我想要的东西!
答案 0 :(得分:2)
您可以编写自己的自定义序列化程序 - 我创建了一个遵循您希望/
成为\\/
的规则但是如果该字符串已经转义,您希望它保留{{1} }而不是\\/
。
\\\\/
这将从以下字符串创建:
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"`
注册自定义序列化程序
当然,您需要在安装程序中将此序列化程序传递给Gson,如下所示:
"12 \\/first \\/second \\/third\\/fourth\\/\\/fifth"
你可以找到这个答案,我的github stackoverflow中的确切示例回答了repo:
Gson CustomSerializer to escape a String in a special way by DominikAngerer