C# 在字符串中插入变量
如何在字符串中插入变量userName.Im使用C#。我添加了\但找不到它C# 在字符串中插入变量,c#,C#,如何在字符串中插入变量userName.Im使用C#。我添加了\但找不到它 String orderStr = String.Format(@"{ ""currency"":""MXN"", ""customer_info"": { ""name"": ""julio"", ""phone"": ""Cabalos"",
String orderStr = String.Format(@"{
""currency"":""MXN"",
""customer_info"": {
""name"": ""julio"",
""phone"": ""Cabalos"",
""email"": ""el@el.com""
},
""line_items"": [{
""name"": ""\'{0}\'"",
""description"": ""descripc"",
""unit_price"": 233,
""quantity"": '1',
""tags"": [""Transporte"", ""Logistic Cloud""],
""type"": ""physical""
}],
""charges"":[{
""payment_method"": {
""type"": ""oxxo_cash""
}
}]
}", userName);
您必须使用
{{
和}
来转义{
和}
。
您还可以使用互镀字符串($
)
string.Format
的参数使用大括号表示标记,因此JSON将很难使用-您需要执行大量的}
和{{
double。这是在某些字符的正确JSON编码问题之前…@MarcGravel好吧,与双引号的数量相比,这些双括号现在不会增加那么多尴尬;Pha你有没有考虑过使用像Newtonsoft.JSON这样的JSON库来代替字符串插值?这可能会让事情变得更糟继续前进。
string userName = "userName";
String orderStr = $@"{{
""currency"":""MXN"",
""customer_info"": {{
""name"": ""julio"",
""phone"": ""Cabalos"",
""email"": ""el@el.com""
}},
""line_items"": [{{
""name"": ""\'{userName}\'"",
""description"": ""descripc"",
""unit_price"": 233,
""quantity"": '1',
""tags"": [""Transporte"", ""Logistic Cloud""],
""type"": ""physical""
}}],
""charges"":[{{
""payment_method"": {{
""type"": ""oxxo_cash""
}}
}}]
}}";