拼接JSON字符串,有些特殊字符需要替换掉,如果未替换这些特殊字符生成的JSON不会被正确解析
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public static string ToJson(this string s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++) {
char c = s.ToCharArray()[i];
switch (c) {
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default: sb.Append(c); break;
}
}
return sb.ToString();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++) {
char c = s.ToCharArray()[i];
switch (c) {
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default: sb.Append(c); break;
}
}
return sb.ToString();
}
如果未替换这些特殊字符生成的JSON不会被正确解析。