我有一个带双引号的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; }
}
}
答案 0 :(得分:3)
尝试切换json.Replace(@"\""", @"""")
> json.Replace(@"""", @"\""")
答案 1 :(得分:1)
Have a look at what the @ sign does to strings in C#。对于常规字符串,可以使用const FormData = require('form-data')
const data = new FormData()
data.append('quantity', '1')
data.append('offset', '0')
axios({
url: <URL>,
method: 'POST',
data,
headers: {
'API-Authorization': <KEY>
}
})
来对引号(“)进行转义。但是,对于逐字字符串(即以@符号开头的字符串)来说,引号会使用双引号(”“)进行转义。
请注意,JSON支持单引号字符串,因此编写\"
可能更易读。
因此,如果您想编写一个带有两个引号的字符串,则可以将其写为
"''"