2017-07-05 109 views
0

我怎么能插使用C#。我在string.Im变量username添加\但它并没有发现插值变量

String orderStr = String.Format(@"{ 
        ""currency"":""MXN"", 
        ""customer_info"": { 
        ""name"": ""julio"", 
        ""phone"": ""Cabalos"", 
        ""email"": ""[email protected]"" 
        }, 
        ""line_items"": [{ 
        ""name"": ""\'{0}\'"", 
        ""description"": ""descripc"", 
        ""unit_price"": 233, 
        ""quantity"": '1', 
        ""tags"": [""Transporte"", ""Logistic Cloud""], 
        ""type"": ""physical"" 
        }], 
       ""charges"":[{ 
        ""payment_method"": { 
         ""type"": ""oxxo_cash"" 
        } 
        }] 
       }", userName); 
+0

参数为'string.Format'使用大括号来表示标记,所以JSON将是尴尬 - 你需要做** **很多的'}}'和'{{'加倍。这是之前问题的某些字符正确的JSON编码... –

+0

@MarcGravell那么,与双引号的数目相比,这些双花括号现在不会增加那么多尴尬; P – poke

+1

你有没有考虑过使用json库像Newtonsoft.Json而不是字符串插值?这可能会让事情变得更容易。 –

回答

1

你必须逃离{}{{}} 。 您也可以使用interoplated字符串($

string userName = "userName"; 
String orderStr = [email protected]"{{ 
     ""currency"":""MXN"", 
     ""customer_info"": {{ 
     ""name"": ""julio"", 
     ""phone"": ""Cabalos"", 
     ""email"": ""[email protected]"" 
     }}, 
     ""line_items"": [{{ 
     ""name"": ""\'{userName}\'"", 
     ""description"": ""descripc"", 
     ""unit_price"": 233, 
     ""quantity"": '1', 
     ""tags"": [""Transporte"", ""Logistic Cloud""], 
     ""type"": ""physical"" 
     }}], 
    ""charges"":[{{ 
     ""payment_method"": {{ 
      ""type"": ""oxxo_cash"" 
     }} 
     }}] 
    }}"; 
+0

感谢它的工作。 – Eliuber