简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM