如何从存在重复id的JObject中提取definition为Document的id列表
问题原因
- 原代码JSONPath语法错误:
$entities.id不符合JSONPath规范,根节点访问属性需要加.,且该写法仅能获取顶层entities的id,无法过滤definition为Document的节点、无法处理嵌套Document场景,也无法排除Author属性下的无效id。 - 输出
System.Collections.Generic.List1[System.String]是因为你直接对返回的List对象调用了ToString()`,属于调用端打印逻辑错误,和方法返回值无关。
修正后的实现代码
using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; public static List<string> GetAllDocIds(string json) { List<string> returnList = new List<string>(); JObject root = JObject.Parse(json); // 遍历所有层级节点,筛选符合条件的Document实体 var validDocs = root.Descendants() .OfType<JObject>() .Where(entity => // 筛选definition为Document的实体 entity["definition"]?.ToString() == "Document" // 排除所有归属在name=Author属性下的实体 && !entity.Ancestors() .OfType<JObject>() .Any(ancestor => ancestor["name"]?.ToString() == "Author") ); foreach (var doc in validDocs) { returnList.Add(doc["id"].ToString()); } return returnList; }
正确打印方式
遍历返回的列表输出每个id即可,不要直接对List执行ToString:
List<string> docIds = GetAllDocIds(你的JSON字符串); // 单个打印 foreach(string id in docIds) { Console.WriteLine(id); } // 合并为分隔符分隔输出 Console.WriteLine(string.Join("、", docIds));
实现逻辑说明
- 用
Descendants()方法递归遍历JSON所有层级的节点,天然支持Document嵌套在其他Document内部的场景 - 两层过滤条件:首先筛选出
definition字段等于Document的实体,再排除所有祖先节点中存在name=Author属性的实体,完全过滤掉Author下的无效id - 最终收集所有符合条件的实体id返回,测试场景下返回结果就是
["45","46","47"]
内容的提问来源于stack exchange,提问作者Tree55Topz
相关产品推荐
相关产品推荐

