我有一个 JSON 数组,我想分阶段过滤它。数组示例如下
[
{
"env": "ENG",
"details": [
{
"Id": 3,
"Name": "TestA",
"programs": [
{
"name": "TestA",
"type": "AA"
}
]
},
{
"tenantId": 5,
"tenantName": "Demo",
"programs": [
{
"name": "DEMO",
"type": "BB"
},
{
"name": "DEMO2",
"type": "BB"
}
]
}
]
},
{
"env": "Span",
"details": [
{
"tenantId": 4,
"tenantName": "Cat",
"programs": [
{
"name": "CAT",
"type": "123"
}
]
},
{
"tenantId": 5,
"tenantName": "Demo",
"programs": [
{
"name": "DEMOSpan",
"type": "www"
},
{
"name": "DEMOU2",
"type": "eee"
}
]
}
]
}
]
对于第一阶段,我想首先通过顶层过滤数组,这是示例中的 env,所以说 ENG,所以它返回:
{
"env": "ENG",
"details": [
{
"Id": 3,
"Name": "TestA",
"programs": [
{
"name": "TestA",
"type": "AA"
}
]
},
{
"tenantId": 5,
"tenantName": "Demo",
"programs": [
{
"name": "DEMO",
"type": "BB"
},
{
"name": "DEMO2",
"type": "BB"
}
]
}
]
}
最后想按 Id 或 Name 过滤结果数组,假设我选择按 Name=TestA 过滤。我正在寻找的结果是整个单个数组,如下所示:
{
"Id": 3,
"Name": "TestA",
"programs": [
{
"name": "TestA",
"type": "AA"
}
]
}
在 C# 中解决这个问题的最佳方法是什么?
蒂亚
一种使用方法
System.Text.Json
var foo = JsonSerializer.Deserialize<JsonArray>(json) ?? throw new JsonException("Unable to deserialize JSON.");
var bar = foo.Where(n => n?["env"]?.GetValue<string>() == "ENG");
var baz = bar?.SelectMany(n => n?["details"]?.AsArray() ?? [])
.FirstOrDefault(n => n?["Name"]?.GetValue<string>() == "TestA");