我正在尝试将动态参数传递给JSON Post请求,但是当我调试时,我在响应中收到BadRequest
格式错误。似乎我无法以正确的样式来格式化“产品”列表,并且输出不像样本格式
我的JSON请求必须类似于以下示例:
{
"token": "[access Token]",
"userid": "[phone number]",
"transactionid": "a integer number",
"products": {
"1221": "100", //product id:product price
"1575": "200" //product id:product price
}
}
这是我的代码:
internal void cashback( Order order,string Atoken)
{
var client = new RestClient(@"link");
RestRequest req = new RestRequest();
var dic = new Dictionary<string, string>();
foreach (var orderitem in order.OrderItems)
{
var product = orderitem.Product;
var score = product.price;
var id = product.id.ToString();
dic.Add(id,score.ToString());
}
req.AddHeader("Content-Type", @"application/json");
req.AddHeader("Accept", @"application/json");
req.RequestFormat = DataFormat.Json;
req.Method = Method.POST;
req.AddParameter("token" , Atoken);
req.AddParameter("userid", "123456");
req.AddParameter("transactionid", "123456");
req.AddParameter("products",x);
var response = client.Execute(req);
string restostr = response.Content.ToString();
}
和订单类包含订单和订单项的详细信息:
public Guid orderGuid { get; set; }
public virtual ICollection<OrderItem> OrderItems
{
get { return _orderItems ?? (_orderItems = new List<OrderItem>()); }
protected set { _orderItems = value; }
}
和订单项:
public decimal price{ get; set; }
public int id{ get; set; }
和错误: 状态码
BadRequest System.Net.HttpStatusCode
答案 0 :(得分:1)
似乎您有错字:
您在这里写的产品没有't'
{
"token": "[access Token]",
"userid": "[phone number]",
"transactionid": "a integer number",
"producs": { // <<=== producs without t
"1221": "100",
"1575": "200"
}
}
您在这里用't'书写产品
req.AddHeader("Content-Type", @"application/json");
req.AddHeader("Accept", @"application/json");
req.RequestFormat = DataFormat.Json;
req.Method = Method.POST;
req.AddParameter("token" , "token code");
req.AddParameter("userid", "123456");
req.AddParameter("transactionid", "123456");
req.AddParameter("products",x); // <<<=== products with 't'
var response = client.Execute(req);
string restostr = response.Content.ToString();
答案 1 :(得分:1)
我们需要知道什么是“订单”类型来帮助您,但是假设像“ dic”变量那样的2型字典可能以这种方式编写可以帮助您解决问题:
List<Object> me = new List<Object>();
foreach (var x in dic)
{
object product = new object{x.Key, x.Value};
me.Add(product);
}
[...]
req.AddParameter("products",me);
答案 2 :(得分:1)
{
"token": "[access Token]",
"userid": "[phone number]",
"transactionid": "a integer number",
"products": {
"1221": "100", //product id:product price
"1575": "200" //product id:product price
}
我必须像打击一样将参数添加到jsonbody
中:
var dict = new Dictionary<string, string>();
foreach (var x in order.OrderItems)
{
var price= (x.price);
var id = x.id.ToString();
dict.Add(id,price.ToString("F"));
}
req.AddHeader("Content-Type", @"application/json");
req.AddHeader("Accept", @"application/json");
req.RequestFormat = DataFormat.Json;
req.Method = Method.POST;
req.AddJsonBody(new
{
token = Atoken,
userid = "123456",
transactionid = "123456",
productlist=dict
});