【问题标题】:How to add escaping character "\"?如何添加转义字符“\”?
【发布时间】:2020-09-04 23:38:44
【问题描述】:

我有一个带双引号的 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 的参数按什么顺序排列? (如果这没有意义,请查看文档。)

标签: c# json


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Have a look at what the @ sign does to strings in C#。对于常规字符串,您可以使用 \" 转义引号 (")。但是对于逐字字符串(即以 @ 符号开头的字符串),引号会使用双引号 ("") 进行转义。

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

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

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

    Try it online.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多