[英]How take this json path in newtonsoft.json C#
我一直在構建一個將通過用戶API提供JSON的應用程序。 它應該使用JSONPath從JSON讀取數據並保留所選部分。 我正在嘗試使用Json.Net
(Newtonsoft)來做到這一點。 以下JSON是示例:
{
// other properties here and different structure here
"Data": [
{
"Code": "625087",
"Name": "Customer Name",
"Email": "test@hfgidfgd.com"
},
{
"Code": "625087",
"Name": "Customer Name",
"Email": "test@hfgidfgd.com"
},
{
"Code": "625087",
"Name": "Customer Name",
"Email": "test@hfgidfgd.com"
}
],
// other properties here and different structure here
}
我想使用JSONPath提取由Data
屬性內容提供的數組,並將其轉換為List<Dictionary<string, object>>
以便在我的應用程序中進行操作。
在jsonpath.com之類的工具中,以下JSONPath查詢可以正常工作,但對於Newtonsoft則無法:
// get that json
string content = GetJson();
var jo = JObject.Parse(content);
var jsonPath = "$..Data.*";
var jsonPathResult = jo.SelectTokens(jsonPath, true /* to get error when it is not found */ );
相反,我得到了例外:
屬性“ *”在JArray上無效。
如果我像這樣執行JSONPath:
var jsonPath = "$..Data"; // same for just: "Data"
var jsonPathResult = jo.SelectTokens(jsonPath);
我必須使用兩個嵌套的foreach循環搜索結果,我認為這不是一個優雅的解決方案:
var result = new List<Dictionary<string, object>>();
foreach (var jsonResult in jsonPathResult)
{
foreach (var item in jsonResult)
{
var fields = JsonConvert.DeserializeObject<Dictionary<string, object>>(item.ToString());
// some adjusts on the fields dictionary will be applied here...
result.Add(fields);
}
}
是否有任何方法可以使結果僅通過Data
屬性的內容進行單循環?
如JSONPath-XPath for JSON中所示 ,數組元素通配符的語法為[*]
。 因此,您的代碼應如下所示:
var jsonPath = "$..Data[*]";
var result = jo.SelectTokens(jsonPath, true /* to get error when it is not found */ )
.Select(o => o.ToObject<Dictionary<string, object>>())
.ToList();
在這里,我使用JToken.ToObject<T>()
將每個數組元素直接反序列化為Dictionary<string, object>>
而無需重新序列化為字符串。
樣本工作.Net提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.