使用C#反序列化复杂嵌套JSON并提取第二层hits节点数据
C# 提取嵌套JSON第二层hits数组的实现方案
你要提取的目标路径为 根节点.hits.hits,以下是两种常用C# JSON解析库的实现方式:
使用Newtonsoft.Json(Json.NET)实现
首先通过NuGet安装 Newtonsoft.Json 包。
快速动态解析(无需定义实体类)
using Newtonsoft.Json.Linq; // jsonStr为你获取的完整JSON字符串 JObject rootObj = JObject.Parse(jsonStr); // 直接获取第二层hits数组 JArray targetHits = (JArray)rootObj["hits"]["hits"]; // 遍历数组读取字段示例 foreach (var hitItem in targetHits) { // 读取索引字段 string index = hitItem["_index"]?.ToString(); // 读取_source下的标题字段 string title = hitItem["_source"]["title"]?.ToString(); // 读取locationList第一个元素的城市字段 string city = hitItem["_source"]["locationList"][0]["city"]?.ToString(); }
强类型解析(适合生产环境,类型安全)
先定义和JSON结构匹配的实体类(不需要用到的字段可以省略不定义):
using Newtonsoft.Json; public class EsResponse { [JsonProperty("hits")] public EsHitsParent HitsParent { get; set; } } public class EsHitsParent { [JsonProperty("hits")] public List<EsHitItem> TargetHits { get; set; } } public class EsHitItem { [JsonProperty("_index")] public string Index { get; set; } [JsonProperty("_id")] public string Id { get; set; } [JsonProperty("_score")] public double Score { get; set; } [JsonProperty("_source")] public EsSourceData Source { get; set; } } public class EsSourceData { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("businessName")] public string BusinessName { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("locationList")] public List<EsLocation> LocationList { get; set; } } public class EsLocation { [JsonProperty("country")] public string Country { get; set; } [JsonProperty("city")] public string City { get; set; } [JsonProperty("address")] public string Address { get; set; } }
反序列化代码:
EsResponse esResult = JsonConvert.DeserializeObject<EsResponse>(jsonStr); // 直接拿到强类型的hits集合 List<EsHitItem> targetHits = esResult.HitsParent.TargetHits;
使用System.Text.Json实现
适合.NET Core 3.0+ / .NET 5+ 版本,框架原生自带无需额外安装包。
快速动态解析
using System.Text.Json; using JsonDocument doc = JsonDocument.Parse(jsonStr); JsonElement root = doc.RootElement; JsonElement targetHits = root.GetProperty("hits").GetProperty("hits"); // 遍历数组读取字段示例 foreach (JsonElement hitItem in targetHits.EnumerateArray()) { string index = hitItem.GetProperty("_index").GetString(); string title = hitItem.GetProperty("_source").GetProperty("title").GetString(); }
强类型解析
实体类的特性替换为JsonPropertyName即可:
using System.Text.Json.Serialization; public class EsResponse { [JsonPropertyName("hits")] public EsHitsParent HitsParent { get; set; } } public class EsHitsParent { [JsonPropertyName("hits")] public List<EsHitItem> TargetHits { get; set; } } // 其余实体类同理替换特性即可
反序列化代码:
EsResponse esResult = JsonSerializer.Deserialize<EsResponse>(jsonStr); List<EsHitItem> targetHits = esResult.HitsParent.TargetHits;
内容的提问来源于stack exchange,提问作者m0nsterr
相关产品推荐
相关产品推荐

