使用Newtonsoft.Json反序列化收到的字串爲JObject或其它支持的數據模型,有時錯誤,提示以下:html
Bad JSON escape sequence: \c. Path 'idno', line 5, position 34.
甚納悶之。遂搜索資料,略有小獲,其非法分界符所致。合法的分隔符爲:git
以此爲依據,對字串作正則替換,問題解決,錄代碼以記之。github
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(); }
結果如圖:json
參考資料:ui
How to escape special characters in building a JSON string? - Stack Overflowurl