将变量传递给JSON请求正文的逐字字符串文字

时间:2019-08-13 20:33:15

标签: c# json

对C#来说还很陌生,我正在尝试使用逐字字符串文字来构建整洁的多行字符串,而且还尝试将变量传递给它。

说它的格式不正确,所以在这里看到我做错了,因为这种格式与我在其他SO问题中看到的格式很接近。

  var bodyJson =string.Format(@"{
                                  ""ConsultingProject@odata.bind"": ""/consultingprojectses({0})"",
                                  ""buyer_product_id@odata.bind"": ""products(f4b6b505-99df-e711-8108-c4346bdc3201)"",
                                  ""BuyerLookupId@odata.bind"": ""/contacts({1})"",
                                  ""new_buyer_account_id@odata.bind"": ""/accounts({2})""
                                }", projectRecord.consultingprojectsid, contact, projectRecord.account_value);

或者最好是这样:

  var bodyJson =string.Format(@"{
                                  'ConsultingProject@odata.bind': '/consultingprojectses({0})',
                                  'buyer_product_id@odata.bind': 'products(f4b6b505-99df-e711-8108-c4346bdc3201)',
                                  'BuyerLookupId@odata.bind': '/contacts({1})',
                                  'tnew_buyer_account_id@odata.bind': '/accounts({2})'
                                }", projectRecord.consultingprojectsid, contact, projectRecord.account_value);

1 个答案:

答案 0 :(得分:2)

创建一个对象并使用序列化器来构造您的Json:

var obj = new
            {
                Key1 = "value1",
                Key2 = "value2"
            };

var json = JsonConvert.SerializeObject(obj);