将字符串添加到逐字字符串文字

Adding string to verbatim string literal

我正在尝试构建如下所示的原始 json 字符串以在 http 请求中发送它

var requestContent = @"{
                    ""name"": ""somename"",
                    ""address"": ""someaddress""
}";

我希望从下面的变量中提供名称和地址值,而不是硬编码它们

string name = "someName";
string address = "someAddress";

但是下面的不行。有什么想法吗?

var requestContent = @"{
                        ""name"": \" + name \",
                        ""address"": \" + address \"
    }";

正确的语法是:

var requestContent = @"{
    ""name"": """ + name + @""",
    ""address"": """ + address + @"""
}";

或者,您可以使用 string.Format:

var requestContent = string.Format(@"{
    ""name"": ""{0}"",
    ""address"": ""{1}""
}", name, address);

或者您可以使用实际的 JSON 序列化程序。

而是使用Newtonsoft.JSON JObject(),如

dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";

Console.WriteLine(myType.ToString());

将生成 JSON 字符串为

 {
  "name": "Elbow Grease",
  "address": "someaddress"
 }

您也可以将逐字字符串与插值一起使用:

var requestContent = $@"{{
    ""name"": ""{name}"",
    ""address"": ""{address}""
}}";

编辑:为此,您必须确保输出中所需的大括号加倍(就像引号一样)。另外,首先 $,然后 @