API反序列化后无法引用Booking中Item的startTime字段求助
问题描述
已通过JsonConvert.DeserializeObject将API返回的JSON反序列化为Root类实例,目前可正常调用Booking类的所有属性,但无法访问其中Item列表内的startTime字段——调试时能确认该字段数据存在,求正确的引用方式。
代码示例
var APIContent = response.Content.ReadAsStringAsync().Result; Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(APIContent);
实体类定义
public class Booking { public string bookingReference { get; set; } public string uniqueId { get; set; } public DateTime createdDate { get; set; } public string status { get; set; } public string name { get; set; } public int customerId { get; set; } public double total { get; set; } public List<Item> items { get; set; } public List<object> customerFlags { get; set; } } public class Item { public int productId { get; set; } public int quantity { get; set; } public string bookingDate { get; set; } public string startTime { get; set; } } public class Root { public List<Booking> bookings { get; set; } }
JSON示例片段
{ "bookings": [ { "bookingReference": "13092675", "uniqueId": "1537d669-1a11-487a-b132-b9198a822956", "createdDate": "2024-03-10T18:26:16.943Z", "status": "Paid", "name": "Test Data", "customerId": 3737676, "total": 321.35, "items": [ { "productId": 188460, "quantity": 20, "bookingDate": "2024-03-15", "startTime": "11:00" } ], "customerFlags": [] } ] }
解决方案
核心原因是Root.bookings和Booking.items都是集合类型(List),不能直接通过.链式访问集合内元素的属性,必须通过索引定位或遍历集合来获取目标Item实例,再访问其startTime。
1. 索引访问(已知元素位置时)
直接通过下标定位集合中的元素,适合确定集合非空且元素位置明确的场景:
// 获取第一个Booking的第一个Item的startTime string targetStartTime = myDeserializedClass.bookings[0].items[0].startTime;
2. 遍历集合(批量处理场景)
通过foreach循环遍历所有Booking和Item,逐个访问startTime:
foreach (var booking in myDeserializedClass.bookings) { foreach (var item in booking.items) { string currentStartTime = item.startTime; // 此处添加你的业务处理逻辑 } }
3. 安全访问(避免空引用异常)
实际开发中要先判断集合是否为空、是否有元素,防止NullReferenceException:
if (myDeserializedClass?.bookings != null && myDeserializedClass.bookings.Any()) { foreach (var booking in myDeserializedClass.bookings) { if (booking?.items != null && booking.items.Any()) { foreach (var item in booking.items) { string safeStartTime = item.startTime; // 业务处理 } } } }
内容的提问来源于stack exchange,提问作者Steven White
相关产品推荐
相关产品推荐

