Newtonsoft.Json反序列化为自定义JObject提取Pinpoint节点
错误原因
你的代码抛出Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject异常,核心问题有3个:
- 没有遍历
Viewpoints数组下的单个子项,直接对数组子节点集合取["Pinpoint"]["Position"]得到的是枚举结果,无法直接传入JObject构造函数 - 没有做
Pinpoint字段的存在性判断,会把无该字段的节点纳入处理 - 逻辑只提取了
Position字段,和你需要保留完整Viewpoint对象(含Id、IssueId、Pinpoint)的需求不符
可行实现方案
直接操作Newtonsoft.Json的LINQ to JSON对象即可,不需要反序列化为dynamic,两层遍历加字段判空就能实现需求:
using Newtonsoft.Json.Linq; // 直接将接口返回字符串解析为JArray JArray sourceIssues = JArray.Parse(response.Content); List<JToken> result = new List<JToken>(); foreach (JObject issue in sourceIssues) { // 取当前问题下的Viewpoints数组,做判空避免字段缺失报错 JArray viewpoints = issue["Viewpoints"] as JArray; if (viewpoints == null) continue; foreach (JObject viewpoint in viewpoints) { // 只保留包含Pinpoint字段的节点 if (viewpoint["Pinpoint"] != null) { result.Add(viewpoint); } } } // 需要输出JSON字符串时直接序列化即可 // string finalJson = JsonConvert.SerializeObject(result, Formatting.Indented);
如果偏好简洁写法,可以用LINQ直接实现筛选:
JArray sourceIssues = JArray.Parse(response.Content); List<JToken> result = sourceIssues .Select(i => i["Viewpoints"] as JArray) .Where(arr => arr != null) .SelectMany(arr => arr) .Where(vp => vp["Pinpoint"] != null) .ToList();
逻辑说明
- 不需要重新构造JObject,符合条件的Viewpoint节点本身就包含
Id/IssueId/Pinpoint三个字段,和你期望的输出结构完全匹配 - 过滤逻辑会自动排除所有不带Pinpoint字段的节点,包括Issue3下的全部Viewpoint、Issue2下第一个无Pinpoint的Viewpoint
- 增加了空值校验,避免接口返回字段缺失时抛出空引用异常
内容的提问来源于stack exchange,提问作者uwponcel
相关产品推荐
相关产品推荐

