.NET Framework项目中C#反序列化无属性标识JSON的问题
适配.NET Framework的无固定属性JSON反序列化方案
核心思路
针对你提供的JSON结构(images数组元素为含动态图片文件名键的单键字典),以下方案基于Newtonsoft.Json(.NET Framework生态下最常用的JSON处理库,兼容所有.NET Framework版本)实现,完全规避高版本C#特性依赖。
方案一:强类型模型解析
1. 模型定义
保持与JSON结构匹配的强类型模型,无需额外特性:
using Newtonsoft.Json; using System.Collections.Generic; public class DetectionModel { // 如果JSON中不存在section字段,可直接删除该属性 public string section { get; set; } public List<Dictionary<string, List<List<double>>>> images { get; set; } = new List<Dictionary<string, List<List<double>>>>(); }
2. 优化后的解析代码
避免原代码中频繁调用ToList()的冗余操作,直接遍历字典键值对:
double[] detectionParams = new double[6]; string sImageName = ""; // 读取并反序列化JSON var jsonContent = File.ReadAllText(sFile); var model = JsonConvert.DeserializeObject<DetectionModel>(jsonContent); foreach (var imageDict in model.images) { // 每个字典仅含一个键值对,直接取第一个条目 var imageEntry = imageDict.First(); sImageName = imageEntry.Key; double max_detection_conf = 0.0; foreach (var detection in imageEntry.Value) { // 复制检测参数到数组 detection.CopyTo(detectionParams, 0); // 更新最高置信度 if (detectionParams[4] > max_detection_conf && detectionParams[5] == 1) { max_detection_conf = detectionParams[4]; } } // 此处可添加对当前图片及最高置信度的业务处理逻辑 // 示例:Console.WriteLine($"图片 {sImageName} 最高有效置信度:{max_detection_conf}"); }
方案二:动态JObject解析(无需定义模型)
如果不需要强类型约束,可直接用Newtonsoft.Json的JObject动态解析,灵活性更高:
using Newtonsoft.Json.Linq; using System.IO; var jsonContent = File.ReadAllText(sFile); var rootObj = JObject.Parse(jsonContent); var imagesArray = rootObj["images"] as JArray; foreach (var imageObj in imagesArray) { // 获取动态图片名和对应的检测数组 var imageProp = imageObj.First as JProperty; string sImageName = imageProp.Name; var detections = imageProp.Value as JArray; double max_detection_conf = 0.0; foreach (var detection in detections) { double[] detectionParams = detection.ToObject<double[]>(); if (detectionParams[4] > max_detection_conf && detectionParams[5] == 1) { max_detection_conf = detectionParams[4]; } } // 业务处理逻辑 // 示例:Console.WriteLine($"图片 {sImageName} 最高有效置信度:{max_detection_conf}"); }
兼容性说明
- 以上方案兼容**.NET Framework 4.0及以上版本**,仅需通过NuGet安装
Newtonsoft.Json包即可。 - 无任何C#版本特性依赖,完全适配旧版项目环境。
内容的提问来源于stack exchange,提问作者SimonKravis
相关产品推荐
相关产品推荐

