[英]How to escape slashes in Gson
根據json規范,轉義“ /
”是可選的。
Gson默認情況下不執行此操作,但是我正在處理期望轉義為“ /
”的Web服務。 所以我要發送的是“ 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 stackoverflow答案回購中找到此答案和確切的示例:
Gson CustomSerializer通過DominikAngerer以特殊方式轉義字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.