You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Newtonsoft.Json.Linq筛选outcome_id为4的所有JSON令牌?

使用Newtonsoft.Json.Linq筛选outcome_id=4的JSON元素

哈哈,这问题我之前也碰到过,用Newtonsoft.Json.Linq自带的LINQ查询能力就能轻松搞定,我给你一步步说清楚:

步骤1:解析JSON字符串为JArray

首先你需要把从服务器拿到的JSON字符串解析成JArray对象,这是处理JSON数组的基础:

// 假设你的JSON数据已经存放在这个字符串里
string jsonData = "[ { \"outcome_id\": \"4\", \"items\": [ { \"outcome_item_id\": \"4\", \"outcome_sport_id\": \"311\" } ] }, { \"outcome_id\": \"4\", \"items\": [ { \"outcome_item_id\": \"4\", \"outcome_sport_id\": \"312\" } ] }, { \"outcome_id\": \"5\", \"items\": [ { \"outcome_item_id\": \"4\", \"outcome_sport_id\": \"313\" } ] } ]";
JArray outcomeArray = JArray.Parse(jsonData);

步骤2:筛选outcome_id等于"4"的元素

接下来用LINQ的Where方法就能精准筛选出符合条件的JObject:

// 基础筛选写法
var filteredOutcomes = outcomeArray
    .Where(jo => jo["outcome_id"].Value<string>() == "4")
    .ToList();

如果担心JSON里可能存在没有outcome_id字段的情况,可以加个空值检查,避免空引用异常:

// 更严谨的筛选写法(处理字段缺失的情况)
var filteredOutcomes = outcomeArray
    .Where(jo => jo["outcome_id"] != null && jo["outcome_id"].Value<string>() == "4")
    .ToList();

额外:如果需要提取筛选结果里的items

要是你还想把这些outcome_id=4的元素里的items都取出来,用SelectMany就能一键扁平化:

var allItemsFromOutcome4 = filteredOutcomes
    .SelectMany(jo => jo["items"].Children<JObject>())
    .ToList();

这样你就得到所有属于outcome_id=4的子items了~

内容的提问来源于stack exchange,提问作者FireFalcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:35:31