2017-07-05 147 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