linasster
linasster

Reputation: 149

How to add escaping character "\"?

I have a JSON string with double-quotes. I need to send the string further to another application. In order for another application to read it, I need to escape double-quotes. for this, I tried to use the Replace() method but in the console it any way prints the string without the backslash character. What am I doing wrong? Here is my code:

class Program
    {
        static void Main(string[] args)
        {
            var jobObj = new Source
            {
                url = "http://localhost",
                name = "YourName",
                age = 54,
                username = "Admin",
                password = "Password",              
                
            };

            var json = JsonConvert.SerializeObject(jobObj);
            string jsonstring = json.Replace(@"\""", @"""");

            Console.WriteLine(jsonstring);
            Console.ReadKey();


        }

        public class Source
        {           
            public string url { get; set; }
            public string name { get; set; }
            public int age { get; set; }
            public string username { get; set; }
            public string password { get; set; }
            
        }
    }

Upvotes: 2

Views: 1270

Answers (2)

Slate
Slate

Reputation: 3694

Have a look at what the @ sign does to strings in C#. For a regular string, you can escape a quote (") with \". However with verbatim strings (i.e. strings that start with an @ symbol), quotes are escaped using double quotes ("").

Note that JSON supports single quote strings, so it may be more readable for you to write "''".

So if you wanted to write a string with two quotes, you can either write it as

string standardString = "\"\""; // or
string verbatimString = @""""""; // or
string singleQuotesString = "''";    

Try it online.

Upvotes: 2

Joel Fleischman
Joel Fleischman

Reputation: 434

try to switch the json.Replace(@"\""", @"""") > json.Replace(@"""", @"\""")

Upvotes: 4

Related Questions