2015-04-01 76 views
1

根据json规范,转义“/”是可选的。如何在Gson中跳转斜杠

Gson默认不会这样做,但我正在处理一个期待转义的web服务“/”。所以我想发送的是“somestring\\/someotherstring”。任何想法如何实现这一目标?

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

+0

'字符串someString = “/”; somerstring = someString.replace(“/”,“\\ /”); System.out.println(someString);' 输出: >> \/ – Selim 2015-04-01 17:11:35

+0

@Selim没有帮助。检查我的编辑 – stoefln 2015-04-01 17:58:50

+0

@stoefln Selim的意思是:在序列化之后(即在JSON字符串上)进行替换,而不是之前。 – 2015-04-01 18:22:31

回答

2

答:自定义序列

您可以编写自己的自定义序列化 - 我已创建了一个下面要/\\/的规则,但如果字符串的长度已经逃脱你想让它留下来\\/而不是\\\\/

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计算器答案回购的具体例子:

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


参见