Search code examples
c#jsonreplacestripslashes

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.


Solution

  • 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