【问题标题】:Deserialize HTTPClient.ReadAsAsync results into a List of Objects将 HTTPClient.ReadAsAsync 结果反序列化为对象列表
【发布时间】:2019-05-12 07:10:39
【问题描述】:

尝试反序列化从 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 Candidate的定义如下:

  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”元素中?有什么想法吗?

【问题讨论】:

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


    【解决方案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 响应中的一个属性。

    【讨论】:

      【解决方案2】:

      我做这样的事情:

        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>
      

      【讨论】:

      • 你不应该处理你的 HttpClient.... 它应该被用作单例
      • Http 客户端不支持 dispose 对象,不需要 using 子句。
      猜你喜欢
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 2014-10-06
      • 2012-03-07
      • 2023-03-13
      相关资源
      最近更新 更多