gpt4 book ai didi

c# - PostAsJson JsonArray C# Web API

转载 作者:行者123 更新时间:2023-11-30 17:52:07 25 4
gpt4 key购买 nike

我正在尝试使用 BigCommerce API 发布一个名为类别的数组。我收到回复说我的数组 [1] 是无效的 Json 数组。

要进行测试,请转至 https://developer.bigcommerce.com/console产品 > 创建新产品。

这是我的代码:

    public bool CreateNewProduct(string name, string sku, decimal price, decimal weight, List<string> categories = null, string type = "physical", string availability = "available")
{
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, api_key);
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler)
{
BaseAddress = new Uri(baseUrl),
};


Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("name", name);
values.Add("price", price.ToString());
values.Add("weight", weight.ToString());
values.Add("sku", sku);

string cats = string.Empty;

if (categories == null)
{
categories = new List<string>();
categories.Add(GetAllCategories().FirstOrDefault().ID.ToString());
}
else
{
foreach (string theInt in categories)
{
cats += theInt + ",";
}

cats.Remove(cats.Length - 1);

}

values.Add("categories", "[1]");
values.Add("type", type);
values.Add("availability", availability);

string userP = username + ":" + api_key;
byte[] authBytes = Encoding.UTF8.GetBytes(userP).ToArray();
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(authBytes));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string url = "products.json";

HttpResponseMessage response = client.PostAsJsonAsync(url, values).Result;
if (response.IsSuccessStatusCode)
{
Product result = response.Content.ReadAsAsync<Product>().Result;
if (result != null)
{
return true;
}
}

return false;

}

这是我的要求:

POST xyz/api/v2/products.json HTTP/1.1
Authorization: Basic adf
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: x
Content-Length: 132
Expect: 100-continue

{"name":"test product 1","price":"100","weight":"1","sku":"test111","categories":"[1]","type":"physical","availability":"available"}

这是响应:

[{"status":400,"message":"The field 'categories' is invalid.","details":{"invalid_reason":"The provided value is not a valid array."}}]

最佳答案

如果要使用字典发送数组,请使用 Dictionary<string, object>并像这样添加数组本身。

values.Add("categories", new[] { 100, 101 });

这将发布类似 "categories":[100,101] 的 JSON ,这是您应该发送的内容。

关于c# - PostAsJson JsonArray C# Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com