【发布时间】:2018-02-16 21:38:53
【问题描述】:
当我运行这段代码时,我收到以下错误消息:
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“HttpClientSample.Product”,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。也可以将 JsonArrayAttribute 添加到类型中以强制它从 JSON 数组中反序列化。
我以为我告诉我的客户返回一个 JSON……我需要转换我的响应(JsonConvert.DeserializeObject)吗?如果是这样,列表?
使用邮递员的典型响应是:
[
{
"id": "1",
"name": "test",
"inactive": false
},
{
"id": "2",
"name": "test2",
"inactive": false
}
]
谢谢
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace HttpClientSample
{
public class Product
{
public string id { get; set; }
public string name { get; set; }
public bool inactive { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.id, product.name, product.inactive);
}
return product;
}
static void Main()
{
// RunAsync().GetAwaiter().GetResult();
RunAsync().Wait();
}
static async Task RunAsync()
{
// Update port # in the following line.
var byteArray = Encoding.ASCII.GetBytes("user:pass");
client.BaseAddress = new Uri("https://localhost:51075/api/products");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
try
{
Product product = new Product();
// Get the product
product = await GetProductAsync("https://localhost:51075/api/products");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
由您决定出错是否是您的代码的正确行为(我们如何找出您的实际期望?)...您确定标题正是您需要知道的?
-
“典型响应”中的方括号表示(产品项目)列表。因此,您需要相应地更改 ReadAsAsync 方法的通用参数。
-
这只是您期待单个
Product还是Product数组的问题。反序列化你所期望的。看起来您期待一个包含一个元素的数组,但仍需要将其反序列化为数组或其他集合。 -
错误看起来很简单。你有什么不明白的?
-
更新了我期望的响应示例。
标签: c# json async-await httpclient