How to remove slashes from a string in c# or how can i create a string which contains double quotes (")

2.7k Views Asked by At

I am struggling with a string

"[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]"

i need the string exact like this

[{"Item": { "Name": "item1" }, "ShipQuantity": " 50.0000000000000000000", "Total": "10.0000000000000000000"},{"Item": { "Name": "Gratuity" }, "ShipQuantity": " 1.0000000000000000000", "Total": "10.0000000000000000000"}]"

But either not able to remove slashes from it, i tried

var string = "[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]";

string = string.Replace(@"\","");

But its not replacing it.

2

There are 2 best solutions below

0
Rahul Sharma On BEST ANSWER

The best way to remove all escape characters from your JSON string is to use the Regex.Unescape() method. This method returns a new string with no escape characters. Even characters such as \n \t etc are removed.

Make sure to import the System.Text.RegularExpressions namespace:

using System.Text.RegularExpressions

var string = "[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]";

var unescapedstring = Regex.Unescape(string);

More information on this method can be found here

2
Bukk94 On

You are escaping " correctly. There is no issue at all.

var string = "[{\"Item\": { \"Name\": \"item1\" }, \"ShipQuantity\": \" 50.0000000000000000000\", \"Total\": \"10.0000000000000000000\"},{\"Item\": { \"Name\": \"Gratuity\" }, \"ShipQuantity\": \" 1.0000000000000000000\", \"Total\": \"10.0000000000000000000\"}]";

The reason why you are seeing the backsplashes is that you are previewing the output in the debugger, who automatically escapes the double-quotes.