将 HTTPClient.ReadAsAsync 结果反序列化为对象列表

Deserialize HTTPClient.ReadAsAsync results into a List of Objects

正在尝试反序列化从 API 返回的 JSON。响应具有以下格式:

{  
 "items":[  
  {  
     "candidateId":40419,
     "firstName":"Adelaida",
     "lastName":"Banks",

  }
   ....
 ]
}

我正在使用 HttpClient 调用 API:

  List<Candidate> model1 = null;

  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "00000");
  HttpResponseMessage response = await client.GetAsync(MyURL);
  response.EnsureSuccessStatusCode();
  var responseBody = await response.Content.ReadAsStringAsync();


   model1 = JsonConvert.DeserializeObject<List<Candidate>>(responseBody);

而Class候选人定义如下:

  public class Candidate
{
    public string candidateId { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
    public int phone { get; set; }
    public int mobile { get; set; }

}

但我遇到了异常:

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[AirCall.Controllers.Candidate]',因为该类型需要一个 JSON 数组(例如 [1,2,3]) 以正确反序列化。

不知道是不是因为响应中的元素列表在"Items"元素内?有什么想法吗?

您的模型需要如下所示

   public class Model
  {
    public List<Candidate> items { get; set; }
  }
  public class Candidate
  {
    public string candidateId { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
    public int phone { get; set; }
    public int mobile { get; set; }

  }

你需要像这样反序列化它

model1 = JsonConvert.DeserializeObject<Model>(responseBody);

其中 model1 是模型的一个实例。

基本上你的型号不符合json。

"items" 是您显示的 json 回复中的 属性。

我是这样做的:

  using (var client = new HttpClient())
            {
                var apiUrl = _config["MicroService:Base"] + string.Format("/Exam/{0}", examId);

                var response = client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiUrl))
                    .Result;

                if (!response.IsSuccessStatusCode)
                    return Task.FromCanceled<ExamDetails>(new CancellationToken(true));

                var content = response.Content.ReadAsStringAsync().Result;
                return Task.FromResult((DtoExamDetails)JsonConvert.DeserializeObject(content,
                    typeof(ExamDetails)));
            }

我的模型是这样的:

 public class ExamDetails
{
    public int Id { get; set; }
    public string Title { get; set; }
    public long CreateBy { get; set; }
    public string CreateByName { get; set; }
    public long CreateDate { get; set; }

}

甚至您也可以使用这样的列表:

<List<ExamDetails>> instead of <ExamDetails>