[英]How to use JSONPath (or any other option) to query an unnamed JSON array?
REST API服務為我的C#代碼提供以下JSON:
[
{
"contentUri": "https://somewhere.com/aGuid1",
"contentId": "2"
},
{
"contentUri": "https://somewhere.com/aGuid2",
"contentId": "3"
},
{
"contentUri": "https://somewhere.com/aGuid3",
"contentId": "4"
}
]
以上JSON是簡化的,實際響應是一個非常大的字符串,因此字符串操作將是昂貴的和內存密集型。
問題是上面的JSON數組沒有名稱。 所以除非我操縱JSON字符串並為其添加名稱,否則我無法將其解析為JArray。 我想避免這種情況。
我可以完美地將JSON解析為JToken。 現在我喜歡使用JToken.SelectToken和JSONPath在JToken中進行查詢
什么JSONPath返回上面JSON數組中的所有元素?
什么JSONPath返回上面JSON數組中的所有contentUri值?
我嘗試了很多JSONPath查詢,但沒有鎖,因為數組沒有名稱。
您可以非常輕松地將上面的json解析為JArray
:
JArray array = JArray.Parse(jsonString);
要獲取數組中的所有對象,您不需要JSONPath表達式,只需遍歷數組:
foreach (JObject child in array)
{
Console.WriteLine("contentUri: " + (string)child["contentUri"]);
Console.WriteLine("contentId: " + (string)child["contentId"]);
}
為了完整性,獲取所有數組值的等效JSONPath表達式為[*]
。 但它並沒有真正給你買任何東西。
要僅獲取所有contentUri
值,可以將SelectTokens
與JSONPath [*].contentUri
:
foreach (JToken uri in array.SelectTokens("[*].contentUri"))
{
Console.WriteLine(uri);
}
或者,您可以像這樣Select
它們:
foreach (string uri in array.Select(t => (string)t["contentUri"]))
{
Console.WriteLine(uri);
}
小提琴: https : //dotnetfiddle.net/C2gIWX
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.