C#怎么从json中筛选数据
时间: 2025-07-05 18:02:58 浏览: 3
### C# 从 JSON 筛选数据
在C#中,通过`Newtonsoft.Json.Linq`命名空间下的类可以方便地解析和筛选JSON数据。下面展示了一个具体的例子,该实例展示了如何利用LINQ表达式来过滤特定条件的数据。
```csharp
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
public class Program {
public static void Main() {
string json = "[{\"Name\":\"John Doe\",\"Age\":30},{\"Name\":\"Jane Smith\",\"Age\":35}]";
JArray jsonArray = JArray.Parse(json);
// 使用 LINQ 过滤年龄大于等于35岁的记录
var filteredNames = from item in jsonArray
where (int)item["Age"] >= 35
select item["Name"].Value<string>();
foreach (var name in filteredNames) {
Console.WriteLine(name);
}
}
}
```
上述代码片段定义了一组JSON数组,并从中选取了所有满足年龄字段值不小于35岁的人的名字[^1]。
对于更复杂的情况,比如处理多层嵌套的JSON结构时,同样可以通过访问相应的键路径来进行深入检索。例如:
```csharp
// 假设有一个更加复杂的JSON对象
string complexJson = @"{
'people': [
{'name': 'Alice', 'details': {'age': 28, 'city': 'New York'}},
{'name': 'Bob', 'details': {'age': 42, 'city': 'Los Angeles'}}
]
}";
JObject jsonObject = JObject.Parse(complexJson);
// 查询居住于洛杉矶且年龄超过40岁的人物名字
var result = from person in jsonObject["people"]
let details = person["details"]
where (int)details["age"] > 40 && (string)details["city"] == "Los Angeles"
select person["name"];
foreach (var r in result) {
Console.WriteLine(r.ToString());
}
```
这段代码说明了即使面对深层次嵌套的对象模型也能够灵活运用LINQ语法实现精准的信息提取。
阅读全文
相关推荐


















