您的位置:首页 > Web前端 > JavaScript

C# JSON带中文字符、转义字符的转换处理

2016-05-18 15:33 387 查看
C# JSON带中文字符、转义字符的转换处理

服务器传入C#数据则转为UTF-8形式,
例如原始数据格式为:data= {“DATA”:[“xp_六脉神剑sword-0”,”xp_九阳神功-1”,”wi_2”,”xp_niubility-2”,”win7_bear-3”]},
在C#内,”六脉神剑”自动转为\xe5\x85\xad\xe8\x84\x89\xe7\xa5\x9e\xe5\x89\x91,
debug调试时,显示C#将\ 自动转义为 \\,即\\xe5\\x85\\xad\\xe8\\x84\\x89\\xe7\\xa5\\x9e\\xe5\\x89\\x91,
(由此可见,C#对于路径的引用时,应将\变为\\或加@,如Close.Image = Image.FromFile(@currentpath + “\image\close1.png”);)

那么JSON中转义字符处理:
需要在JSON转换为dictionary之前,再加入斜杠,具体代码如下:

if (msg.Contains("\\"))
{
msg = msg.Replace("\\", "\\\\");
}


传回数据的时候再反转义:

if (templatename.Contains("\\"))
templatename = Regex.Unescape(templatename);
templatename = System.Text.Encoding.UTF8.GetString(templatename.ToArray().Select(t => Convert.ToByte(t)).ToArray());


引用命名空间:using System.Text.RegularExpressions;

其它字符转义,参考:

http://blog.csdn.net/encienqi/article/details/43992211
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  utf-8 json C# 转义