C#中如何根据JSON动态月份键生成含Job列表的EventMonth模型
实现步骤
你的JSON顶层是动态月份字符串作为键、Job数组作为值的键值对结构,不需要编写复杂的自定义序列化转换器,直接通过字典做中转映射即可,两种常用JSON库的实现方式如下:
方案一:使用 Newtonsoft.Json(Json.NET,第三方常用库)
核心逻辑分两步:
- 先把原始JSON反序列化为
Dictionary<string, List<Job>>类型,字典的键自动对应JSON里的月份字符串,值对应每个月的Job列表 - 用LINQ把字典的键值对投影为
EventMonth对象集合即可
对应代码:
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Globalization; // 替换为你的实际JSON字符串 string rawJson = @"{ ""07-2022"": [], ""08-2022"": [ { ""event_title"": ""asdf"", ""positions"": [ { ""position_title"": ""Graphics Op"" }, { ""position_title"": ""Graphic Design"" } ] } ], ""06-2023"": [] }"; // 反序列化为字典 var monthMapping = JsonConvert.DeserializeObject<Dictionary<string, List<Job>>>(rawJson); // 映射为目标EventMonth列表 List<EventMonth> eventMonthList = monthMapping .Select(item => new EventMonth { month = item.Key, jobs = item.Value ?? new List<Job>() }) // 如果需要按月份先后排序,保留下面这行即可,不需要可以删掉 .OrderBy(em => DateTime.ParseExact(em.month, "MM-yyyy", CultureInfo.InvariantCulture)) .ToList();
方案二:使用 .NET 内置 System.Text.Json
不需要引入第三方依赖,逻辑和上面完全一致:
using System.Text.Json; using System.Collections.Generic; using System.Linq; using System.Globalization; string rawJson = "你的原始JSON字符串"; var monthMapping = JsonSerializer.Deserialize<Dictionary<string, List<Job>>>(rawJson); List<EventMonth> eventMonthList = monthMapping .Select(item => new EventMonth { month = item.Key, jobs = item.Value ?? new List<Job>() }) .OrderBy(em => DateTime.ParseExact(em.month, "MM-yyyy", CultureInfo.InvariantCulture)) .ToList();
说明:代码里加
?? new List<Job>()是为了兼容JSON里某个月份对应值为null的边界情况,避免后续遍历jobs属性时抛出空引用异常。
这种实现方式代码量最少,性能也最优,不需要额外编写自定义JsonConverter逻辑,后续如果JSON新增月份键也能自动映射,不需要修改模型代码。
内容的提问来源于stack exchange,提问作者silversunhunter
相关产品推荐
相关产品推荐

