Reputation: 149
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
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 = "''";
Upvotes: 2
Reputation: 434
try to switch the json.Replace(@"\""", @"""")
> json.Replace(@"""", @"\""")
Upvotes: 4