如何添加转义字符""?



我有一个带双引号的JSON字符串。我需要将字符串进一步发送到另一个应用程序。为了让另一个应用程序阅读它,我需要转义双引号。为此,我尝试使用Replace()方法,但在控制台中,它无论如何都会打印不带反斜杠的字符串。我做错了什么?这是我的代码:

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; }

}
}

尝试切换json.Replace(@"""", @"""")>json.Replace(@"""", @"""")

看看@符号对C#中的字符串做了什么。对于常规字符串,可以使用"转义引号("(。然而,对于逐字逐句的字符串(即以@符号开头的字符串(,引号是使用双引号("(转义的。

请注意,JSON支持单引号字符串,因此编写"''"可能更可读。

所以,如果你想写一个有两个引号的字符串,你可以把它写成

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

在线试用。

最新更新