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

时间:2019-05-12 07:10:39

标签: c# json asp.net-core dotnet-httpclient

尝试反序列化从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);

并且类别候选者的定义如下:

  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”元素之内?有任何想法吗?

2 个答案:

答案 0 :(得分:1)

您的模型需要像这样

   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是Model的实例。

基本上,您的模型与json不匹配。

“ items”是您显示的json响应中的一个属性。

答案 1 :(得分:0)

我做这样的事情:

  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>