如何在C#中解析嵌套JSON并提取可用数据数组?
解决嵌套JSON解析问题,提取指定字段
先梳理你代码里的核心问题:
- 类层级结构错误:JSON根节点的
data是直接包含多个事件对象的数组,不需要额外的dataContainer层级 - 属性名不匹配:
occured_at少了一个字母r,和JSON里的occurred_at不对应 - 嵌套
data字段处理不当:原代码把内层data定义为string类型,会导致解析失败
下面提供两种可行方案,都能帮你提取需要的user_id、created_at和action字段:
方案一:强类型解析(推荐,代码更易维护)
重新定义匹配JSON结构的类,只保留你需要的字段,嵌套的data用JsonElement接收(无需解析内部内容):
using RestSharp; using System.Text.Json; using System.Text.Json.Serialization; class Program { static void Main() { string apiUrl = "https://xxxx/auditlog_events"; var restClient = new RestClient(apiUrl); var request = new RestRequest(""); request.AddHeader("accept", "application/json"); request.AddHeader("authorization", "Bearer xxxx"); var response = restClient.Execute(request); if (response.IsSuccessful) { // 反序列化为强类型对象 var auditResponse = JsonSerializer.Deserialize<AuditResponse>(response.Content!)!; // 遍历事件列表,提取目标字段 foreach (var auditEvent in auditResponse.Data) { Console.WriteLine($"user_id: {auditEvent.UserId}"); Console.WriteLine($"created_at: {auditEvent.CreatedAt}"); Console.WriteLine($"action: {auditEvent.Action}"); Console.WriteLine("---"); } } else { Console.WriteLine($"Error: {response.ErrorMessage}"); } } } // 根响应类 public class AuditResponse { [JsonPropertyName("data")] public List<AuditEvent> Data { get; set; } = new List<AuditEvent>(); } // 审计事件类,仅保留需要的字段 public class AuditEvent { [JsonPropertyName("user_id")] public string UserId { get; set; } = string.Empty; [JsonPropertyName("created_at")] public string CreatedAt { get; set; } = string.Empty; [JsonPropertyName("action")] public string Action { get; set; } = string.Empty; // 嵌套data字段,无需解析内容时用JsonElement接收 [JsonPropertyName("data")] public JsonElement NestedData { get; set; } }
方案二:用JsonNode手动提取(适合快速提取少量字段)
如果不想定义类,可直接通过JsonNode遍历数组提取目标字段:
using RestSharp; using System.Text.Json; using System.Text.Json.Nodes; class Program { static void Main() { string apiUrl = "https://xxxx/auditlog_events"; var restClient = new RestClient(apiUrl); var request = new RestRequest(""); request.AddHeader("accept", "application/json"); request.AddHeader("authorization", "Bearer xxxx"); var response = restClient.Execute(request); if (response.IsSuccessful) { var rootNode = JsonSerializer.Deserialize<JsonNode>(response.Content!)!; // 获取data数组 var eventsArray = rootNode["data"]!.AsArray(); foreach (var eventNode in eventsArray) { // 提取指定字段 string userId = eventNode["user_id"]!.GetValue<string>(); string createdAt = eventNode["created_at"]!.GetValue<string>(); string action = eventNode["action"]!.GetValue<string>(); Console.WriteLine($"user_id: {userId}"); Console.WriteLine($"created_at: {createdAt}"); Console.WriteLine($"action: {action}"); Console.WriteLine("---"); } } else { Console.WriteLine($"Error: {response.ErrorMessage}"); } } }
注意事项
- 确保JSON字段名和C#属性名匹配,或用
[JsonPropertyName]特性实现映射(推荐C#属性用PascalCase,配合特性适配JSON的蛇形命名) - 若字段可能为
null,需注意空引用处理,比如使用!或空值合并运算符??
内容的提问来源于stack exchange,提问作者Sandy Smyth
相关产品推荐
相关产品推荐

