如何在Gson中逃脱斜线 [英] How to escape slashes in Gson
问题描述
根据 json 规范,转义"/
"是可选的.
According to the json specs, escaping "/
" is optional.
Gson默认情况下不执行此操作,但是我正在处理一个预期转义为"/
"的Web服务.所以我要发送的是"somestring\\/someotherstring
".关于如何实现这一目标的任何想法?
Gson does not do it by default, but I am dealing with a webservice which is expecting escaped "/
". So what I want to send is "somestring\\/someotherstring
". Any ideas on how to achieve this?
为了使事情更清楚:如果我尝试用Gson反序列化"\\/
",它将发送"\\\\/
",这不是我想要的 !
To make things clearer: if I try to deserialize "\\/
" with Gson, it will send "\\\\/
", which is not what I want!
推荐答案
答案:自定义序列化程序
您可以编写自己的自定义序列化程序-我创建了一个遵循您希望/
设为\\/
的规则,但是如果字符串已经被转义,则希望它保留\\/
而不是
Answer: The Custom Serializer
You can write your own Custom Serializer - I have created one which follows the rule that you want /
to be \\/
but if the string is already escaped you want it to stay \\/
and not be \\\\/
.
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();
}
}
这将从以下字符串创建:
This will create from the following String:
"12 /first /second \\/third\\/fourth\\//fifth"`
输出:
"12 \\/first \\/second \\/third\\/fourth\\/\\/fifth"
注册您的自定义序列化程序
当然,您需要像下面这样在安装程序中将此序列化器传递给Gson:
Than of course you need to pass this serializer to Gson on Setup like this:
Gson gson = new GsonBuilder().registerTypeAdapter(String.class, new EscapeStringSerializer()).create();
String json = gson.toJson(yourObject);
可下载的&可执行示例
您可以在我的github stackoverflow答案回购中找到此答案和确切的示例:
Downloadable & executable Example
You can find this answer and the exact example in my github stackoverflow answers repo:
Gson CustomSerializer可以在DominikAngerer的特殊方式
这篇关于如何在Gson中逃脱斜线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!