我从数据库查询中获取一个JSON字符串,该数据库查询从多个表中选择数据并返回记录列表,然后将JSON设为,
var result = db.Database.SqlQuery<JobNoQ>(query).ToList();
string json = JsonConvert.SerializeObject(result);
然后我开始关注JSON:
"[{\"S1\":\"1\",\"S2\":\"202010010\",\"S30\":\"COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA\",\"S31\":\"Coca cola 1\",\"D1\":\"2015-07-01T00:00:00\",\"S5\":\"001\",\"S32\":\"Local\",\"S6\":\"T1\",\"S33\":\"By Road\",\"S10\":\"\"},
{\"S1\":\"3\",\"S2\":\"202010010\",\"S30\":\"COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA\",\"S31\":\"Coca cola 1\",\"D1\":\"2015-07-01T00:00:00\",\"S5\":\"002\",\"S32\":\"Innter City\",\"S6\":\"T1\",\"S33\":\"By Road\",\"S10\":\"\"},
{\"S1\":\"4\",\"S2\":\"202010010\",\"S30\":\"COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA\",\"S31\":\"Coca cola 1\",\"D1\":\"2015-07-01T00:00:00\",\"S5\":\"003\",\"S32\":\"International\",\"S6\":\"T2\",\"S33\":\"By Sea\",\"S10\":\"\"}
]"
我想从此数组中删除\。我试过以下:
1. string json = json.Replace("\"", " "); // It removes \ and all "" from the array. I only want to remove the \
2. string json = json.Replace(@"\", " "); // It does nothing
答案 0 :(得分:3)
您的JSON中没有任何反斜杠,这就是为什么用@"\"
替换" "
无效。您的调试器很有用但令人困惑地将您的JSON字符串转换为C#字符串语法,这意味着您的调试器在您看到的任何\
之前添加"
。如果你真的让你的代码打印出JSON字符串,你会发现它们不存在。
答案 1 :(得分:2)
C#中的\
反斜杠就是所谓的escape character。您必须添加另一个斜杠以逃避现有斜杠:
string json = @"Test\string\replace";
json = json.Replace("\\", " ");
Console.WriteLine(json);
输出:
测试字符串替换
使用OP的字符串:
var result = db.Database.SqlQuery<JobNoQ>(query).ToList();
string json = JsonConvert.SerializeObject(result);
json = json.Replace("\\", " ");
Console.WriteLine(json);
输出:
[{ "S1 ": "1 ", "S2 ": "202010010 ", "S30 ": "COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA ", "S31 ": "Coca cola 1 ", "D1 ": "2015-07-01T00:00:00 ", "S5 ": "001 ", "S32 ": "Local ", "S6 ": "T1 ", "S33 ": "By Road ", "S10 ": " "},
{ "S1 ": "3 ", "S2 ": "202010010 ", "S30 ": "COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA ", "S31 ": "Coca cola 1 ", "D1 ": "2015-07-01T00:00:00 ", "S5 ": "002 ", "S32 ": "Innter City ", "S6 ": "T1 ", "S33 ": "By Road ", "S10 ": " "},
{ "S1 ": "4 ", "S2 ": "202010010 ", "S30 ": "COCA COLA BEVERAGES PAKISTAN LTD. GUJRANWALA ", "S31 ": "Coca cola 1 ", "D1 ": "2015-07-01T00:00:00 ", "S5 ": "003 ", "S32 ": "International ", "S6 ": "T2 ", "S33 ": "By Sea ", "S10 ": " "}
]