Newtonsoft.Json反序列化(Deserialize)出错:Bad JSON escape sequence

时间:2023-03-09 03:01:36
Newtonsoft.Json反序列化(Deserialize)出错:Bad JSON escape sequence

使用Newtonsoft.Json反序列化收到的字串为JObject或其它支持的数据模型,有时错误,提示如下:

Newtonsoft.Json反序列化(Deserialize)出错:Bad JSON escape sequence

Bad JSON escape sequence: \c. Path 'idno', line , position .

甚纳闷之。遂搜索资料,略有小获,其非法分界符所致。合法的分隔符为:

Newtonsoft.Json反序列化(Deserialize)出错:Bad JSON escape sequence

以此为依据,对字串做正则替换,问题解决,录代码以记之。

        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();
}

结果如图:

Newtonsoft.Json反序列化(Deserialize)出错:Bad JSON escape sequence

参考资料:

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高级用法 - 焰尾迭 - 博客园