如何将API返回的JSON正确反序列化为自定义C#对象
解决C# JSON反序列化无法映射requesters数组内容的问题
你当前的C#调用API代码:
using (HttpResponseMessage response = client.GetAsync(postMethod.ToString()).Result) { if (response.IsSuccessStatusCode) { var Json = response.Content.ReadAsStringAsync().Result; Console.WriteLine(Json); var y = JsonSerializer.Deserialize<PersonInfoJson>(Json); Console.Write("r= " + y.requester); Console.Write("id= " + y.id); } }
API返回的JSON结构:
{"requesters":[{"active":true,"address":null,"background_information":null,"can_see_all_changes_from_associated_departments":false,"can_see_all_tickets_from_associated_departments":false,"created_at":"2022-12-15T21:07:22Z","custom_fields":{"blah_id":"00002342"},"department_ids":[1111111],"department_names":["Student"],"external_id":null,"first_name":"mike","has_logged_in":false,"id":123456,"is_agent":false,"job_title":null,"language":"en","last_name":"ishere","location_id":null,"location_name":null,"mobile_phone_number":"111-111-1111","primary_email":"email@email.com","reporting_manager_id":null,"secondary_emails":["anotheremail@email.com"],"time_format":"12h","time_zone":"Eastern Time (US & Canada)","updated_at":"2023-02-03T16:59:41Z","vip_user":false,"work_phone_number":"222-222-2222"}]}
你定义的PersonInfoJson类:
public partial class PersonInfoJson { public string requester { get; set; } public string department_names { get; set; } public string first_name { get; set; } public string job_title { get; set; } public string last_name { get; set; } public string mobile_phone_number { get; set; } public string primary_email { get; set; } public string secondary_emails { get; set; } public string work_phone_number { get; set; } public DateTime updated_at { get; set; } public int id { get; set; } }
执行反序列化后,整个JSON被存入y.requester字段,无法正确映射requesters数组内的属性。
问题原因
- 结构不匹配:JSON的顶层是包含
requesters数组的对象,但你的类定义了requester(单数)字符串字段,名称和类型都不兼容,导致序列化器将整个JSON内容作为字符串赋值给requester。 - 字段类型错误:
department_names和secondary_emails在JSON中是数组,你定义为string,即使结构匹配也无法正确映射。
解决方案
1. 修正类结构
需要定义两个类:一个对应JSON的顶层结构,一个对应requesters数组中的单个对象(按需保留字段即可):
// 顶层根类,匹配JSON整体结构 public class RequestersRoot { public List<PersonInfo> requesters { get; set; } } // 匹配requesters数组中的单个对象 public class PersonInfo { public int id { get; set; } public string first_name { get; set; } public string last_name { get; set; } public string primary_email { get; set; } public List<string> department_names { get; set; } public List<string> secondary_emails { get; set; } public string mobile_phone_number { get; set; } public string work_phone_number { get; set; } public DateTime updated_at { get; set; } // 如需其他字段,直接从JSON中复制字段名并定义对应类型即可 }
注意:字段名必须和JSON完全一致(大小写敏感,可通过序列化选项忽略大小写);数组类型字段需定义为
List<T>;可空值类型(如int?)用于处理JSON中可能为null的数字字段。
2. 修改反序列化代码
将反序列化目标改为RequestersRoot,再从数组中提取目标对象:
using (HttpResponseMessage response = client.GetAsync(postMethod.ToString()).Result) { if (response.IsSuccessStatusCode) { var json = response.Content.ReadAsStringAsync().Result; Console.WriteLine(json); // 反序列化为根类 var root = JsonSerializer.Deserialize<RequestersRoot>(json); if (root?.requesters != null && root.requesters.Any()) { // 取数组第一个对象(如需遍历所有对象,改用foreach循环) var person = root.requesters.First(); Console.Write("id= " + person.id); Console.Write("first_name= " + person.first_name); Console.Write("department_names= " + string.Join(", ", person.department_names)); // 其他字段按需输出 } } }
可选:忽略大小写配置
如果JSON字段名和类属性名大小写不一致,可添加序列化选项:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var root = JsonSerializer.Deserialize<RequestersRoot>(json, options);
内容的提问来源于stack exchange,提问作者ghostfly
相关产品推荐
相关产品推荐

