我有一個 JSON 陣列,我需要從該部分的 CustomerId 屬性退出的屬性中獲取 CustomerId 值,我試圖在下面回圈遍歷類別并在其屬性樹中跳過沒有 CustomerId 屬性的那個
var customerId = "";
foreach (var category in JObject.Parse(someData)?["categories"])
{
val = category?["sections"].FirstOrDefault()
?["areas"]?.FirstOrDefault()
?["components"]?.
?["variables"]?.FirstOrDefault()
?["properties"]
?["customerId"]?.ToString();
if (val == null)
continue;
else
{
customerId = val;
break;
}
}
問題是這看起來效率低下(可讀性較差),因為我想有一個不錯.Select的方法可以用來獲得相同的結果,而無需使用 forEach 元素并檢查屬性是否為空。
請注意,這不是我遇到的問題,這是有效的,我只想以更易讀的方式使用Select而不是ForEach.
示例 JSON 資料
{
"categories": [
{
"identifier": "cat1",
"sections": [
{
"identifier": "030615e9-67f9-43ca-a06e-194e7afadccb",
"properties": {},
"areas": [
{
"identifier": "1206f27b-d354-4bfa-9b5e-1fe6b4f7cc83",
"componenets": [
{
"identifier": "49e4550f-8001-4d32-b796-a7ad4423e118",
"type": "Product",
"variables": [
{
"identifier": "0d260417-fa6d-492b-85f1-dc2565bc4805",
"properties": {
"description": ""
}
}
]
}
]
}
]
}
]
},
{
"identifier": "cat2",
"sections": [
{
"identifier": "00b5bfa6-f482-47c2-bdd7-aaac273b7772",
"properties": {},
"areas": [
{
"identifier": "1ca9d051-5ec0-45af-84bc-561cd7620efa",
"componenets": [
{
"identifier": "c73b1e52-3acd-4020-8fc5-adfef7d633b4",
"type": "Customer",
"variables": [
{
"identifier": "0064e872-5c7f-4ec7-a2d6-e8b35b94bd1d",
"properties": {
"customerId": { "Text":"MainId",
"Value":"A12123"
}
}
}
]
}
]
}
]
}
]
}
]
}
uj5u.com熱心網友回復:
另一種方法是使用.SelectTokensJSON.NET 庫(您似乎正在使用它)。假設parsedJson您決議的根物件為JObject:
var customerId = parsedJson.SelectTokens("$.categories..sections..areas..componenets[?(@.type == 'Customer')]..variables..properties.customerId.Value")
.FirstOrDefault()?
.ToString();
這實質上是找到組件型別為“Customer”和屬性“customerId”的第一個條目,并將該 customerId 作為字串回傳。
嚴格來說,您不需要對 type ( [?(@.type == 'Customer')]) 進行查詢,但我的印象就是您想要的。沒有它,查詢將如下所示:
"$.categories..sections..areas..componenets..variables..properties.customerId.Value"
在此處SelectTokens的檔案中查看更多資訊。
uj5u.com熱心網友回復:
如果您想使用與您的問題相同的邏輯,您可以使用下面的代碼。
首先,您遍歷該欄位的所有categories位置。這將產生一個 customerIds 串列,其中有些是,有些可能有值。selectcustomerIdnull
下SingleOrDefault一個從該串列中獲取第一個具有值的專案。這將是您的string customerId.
注意:當您的 json 中沒有 customerId 時,customerId將為null. 如果你想拋出例外而不是使用 null,你可以使用First()代替FirstOrDefault.
var customerId = JObject.Parse(someData)?["categories"]
.Select(category => category?["sections"].FirstOrDefault()
?["areas"]?.FirstOrDefault()?["components"]
?["variables"]?.FirstOrDefault()
?["properties"]
?["customerId"]?.ToString())
.SingleoOrDefault(customerId => customerId != null);
uj5u.com熱心網友回復:
我有一個優化版本:
var pJson = JObject.Parse(someData);
JToken? customerToken = pJson.SelectToken($"$..customerId");
var customerId = customerToken?.ToString();
uj5u.com熱心網友回復:
我首先將 JSON 決議為物件串列,然后使用 Linq 獲取不為空的 CusomerIds 串列。
List<T> arrayItems = jsonBuidler?["categories"].ReadFromJson<List<T>>();
List<string> customerIds = arrayItems.Where(_ => CustomerId != null).Select(_ => _.CustomerId);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533112.html
