使用Newtonsoft.Json反序列化收到的字串为JObject或其它支持的数据模型,有时错误,提示如下:
Bad JSON escape sequence: \c. Path 'idno', line 5, position 34.
甚纳闷之。遂搜索资料,略有小获,其非法分界符所致。合法的分隔符为:
以此为依据,对字串做正则替换,问题解决,录代码以记之。
static void Main(string[] args){string s = @"{""name"": ""王艳"",""sex"": ""女"",""idno"": ""34*****\c0"",""addr"": ""安徽省"",""telephone"": ""no number"",""thumbnail"": ""e:\docs\person\thumbnail\wy.jpg"",""Age"": 27,""DeptName"": ""姚江\R中心""}";//\加bfrnt\/'"为合法分隔符,其它不是,替换string pattern = @"(\\[^bfrnt\\/'\""])";s = Regex.Replace(s, pattern, "\\$1");var jo = JsonConvert.DeserializeObject<JObject>(s);Console.WriteLine(jo.ToString());Console.ReadLine();}
结果如图:
参考资料:
How to escape special characters in building a JSON string? - Stack Overflow
Bad JSON escape sequence: \l. Path 'Transforms[0].Path', line 3, position 45. · Issue #343 · mmanela/chutzpah
Newtonsoft.Json高级用法 - 焰尾迭 - 博客园