Reputation: 1336
I am getting a JSON string from a database query which selects data from multiple tables and return a list of records and then making JSON as,
var result = db.Database.SqlQuery<JobNoQ>(query).ToList();
string json = JsonConvert.SerializeObject(result);
and then I am getting following 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\":\"\"}
]"
I want to remove \ from this array. I have tried following:
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
Upvotes: 1
Views: 133
Reputation:
Your JSON doesn't have any backslashes in it, that's why replacing @"\"
by " "
has no effect. Your debugger is helpfully but confusingly translating your JSON string to the C# string syntax, which means your debugger is adding \
before any "
you see. If you actually let your code print the JSON string, you'll see they aren't there.
Upvotes: 3
Reputation: 8194
The \
backslash in C# is what's called an escape character. You must add another slash to escape the existing one like so:
string json = @"Test\string\replace";
json = json.Replace("\\", " ");
Console.WriteLine(json);
Output:
Test string replace
With OP's string:
var result = db.Database.SqlQuery<JobNoQ>(query).ToList();
string json = JsonConvert.SerializeObject(result);
json = json.Replace("\\", " ");
Console.WriteLine(json);
Output:
[{ "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 ": " "}
]
Upvotes: 2