.NET中如何反序列化JSON并提取PreTaxCost与ResourceGroup
.NET中反序列化JSON并提取PreTaxCost和ResourceGroup数据
下面提供两种.NET环境下常用的实现方案,分别基于System.Text.Json(.NET Core 3.0+内置)和Newtonsoft.Json(第三方常用库)。
方案一:使用System.Text.Json
1. 定义必要实体类
只映射JSON中用到的层级结构,未定义的字段会自动被忽略:
public class CostQueryResult { public Properties Properties { get; set; } } public class Properties { public List<Column> Columns { get; set; } public List<List<object>> Rows { get; set; } } public class Column { public string Name { get; set; } public string Type { get; set; } } // 存储提取后的目标数据 public class CostResourceData { public decimal PreTaxCost { get; set; } public string ResourceGroup { get; set; } }
2. 反序列化并提取数据
using System.Text.Json; using System.Linq; // 假设jsonString是你的JSON原始字符串 string jsonString = @"你的JSON内容"; // 反序列化JSON到实体类 var result = JsonSerializer.Deserialize<CostQueryResult>(jsonString); // 动态获取目标字段的列索引(避免硬编码索引导致列顺序变化时出错) int preTaxCostIndex = result.Properties.Columns.FindIndex(c => c.Name == "PreTaxCost"); int resourceGroupIndex = result.Properties.Columns.FindIndex(c => c.Name == "ResourceGroup"); // 遍历行数据提取目标值 var extractedData = new List<CostResourceData>(); foreach (var row in result.Properties.Rows) { if (preTaxCostIndex != -1 && resourceGroupIndex != -1 && row.Count > Math.Max(preTaxCostIndex, resourceGroupIndex)) { extractedData.Add(new CostResourceData { PreTaxCost = Convert.ToDecimal(row[preTaxCostIndex]), ResourceGroup = row[resourceGroupIndex].ToString() }); } } // 验证提取结果(可根据需求替换为后续业务逻辑) foreach (var item in extractedData) { Console.WriteLine($"资源组:{item.ResourceGroup},税前成本:{item.PreTaxCost}"); }
方案二:使用Newtonsoft.Json
如果你习惯使用Newtonsoft.Json,实现逻辑类似:
1. 实体类与方案一完全一致
复用上面定义的CostQueryResult、Properties、Column和CostResourceData类即可。
2. 反序列化并提取数据
using Newtonsoft.Json; using System.Linq; string jsonString = @"你的JSON内容"; // 反序列化JSON var result = JsonConvert.DeserializeObject<CostQueryResult>(jsonString); // 获取目标字段索引 int preTaxCostIndex = result.Properties.Columns.FindIndex(c => c.Name == "PreTaxCost"); int resourceGroupIndex = result.Properties.Columns.FindIndex(c => c.Name == "ResourceGroup"); // 提取数据 var extractedData = new List<CostResourceData>(); foreach (var row in result.Properties.Rows) { if (preTaxCostIndex != -1 && resourceGroupIndex != -1 && row.Count > Math.Max(preTaxCostIndex, resourceGroupIndex)) { extractedData.Add(new CostResourceData { PreTaxCost = Convert.ToDecimal(row[preTaxCostIndex]), ResourceGroup = row[resourceGroupIndex].ToString() }); } } // 验证输出 foreach (var item in extractedData) { Console.WriteLine($"资源组:{item.ResourceGroup},税前成本:{item.PreTaxCost}"); }
关键说明
- 采用动态获取列索引的方式,避免因JSON中列顺序变化导致提取错误,提升代码健壮性。
- 加入索引有效性和行长度判断,防止数组越界异常。
内容的提问来源于stack exchange,提问作者Sanjuro Watanabe
相关产品推荐
相关产品推荐

