2017-07-31 81 views
1

這是我寫的C#代碼請求數據Restsharp請求參數語法問題

{ 
    "delivery_needed": "false", 
    "merchant_id": "201", 
    "merchant_order_id": "123456", 
    "amount_cents": "25000", 
    "currency": "USD", 
    "items": [], 
    "shipping_data": { 
     "name": "test_user", 
     "street": "sample street", 
     "city": "cairo", 
    } 
} 

的例子,但似乎還有與航運數據,以及項目的語法錯誤。

這是我

錯誤{\ 「shipping_data \」:{\ 「non_field_errors \」:[\ 「資料無效預期一個 字典,卻得到了STR \」]}, \「項目\」:\「預期的項目列表,但 了輸入\\」海峽\\「 \」]}

這是C#代碼我寫的,我很困惑的語法

var client = new RestClient("url"); 
var request = new RestRequest(Method.POST); 
request.AddHeader("content-type", "application/json"); 
request.AddParameter("application/json", request.AddJsonBody(new { delivery_needed = "false", merchant_id = "201", merchant_order_id = "123456", amount_cents = "25000", currency = "USD", items = "[]", shipping_data = "{ ", name = "test_user", street = "sample street", city = "Cairo"}), ParameterType.RequestBody); 
IRestResponse response = client.Execute(request); 

回答

2

您目前正在使用格式錯誤的數據構建請求的正文。

您目前有...shipping_data = "{ ",...這只是一個字符串,因爲它在期待正確的對象模型或鍵/值對(字典)時顯示錯誤。

items根據錯誤信息也沒有正確提供。預計一個數組,但它提供了一個重新串"[]"

你需要建立模型正確

var model = new { 
    delivery_needed = "false", 
    merchant_id = "201", 
    merchant_order_id = "123456", 
    amount_cents = "25000", 
    currency = "USD", 
    items = new object[0], //<--This needs to be an array 
    shipping_data = new { //<--This needs to be a proper object 
     name = "test_user", 
     street = "sample street", 
     city = "Cairo" 
    } 
}; 
var client = new RestClient("url"); 
var request = new RestRequest(Method.POST); 
request.AddHeader("content-type", "application/json"); 
request.AddJsonBody(model); //<-- this will serialize and add the model as a JSON body. 
IRestResponse response = client.Execute(request); 

注意模型的建設被解析爲請求的主體。看看它有多接近OP

+0

的例子,非常感謝您的澄清 –