我有下面的JSON。
[
["Identity"], // 0
["Contact Information"], // 1
["Service Fields"], // 2
["Addresses", "Bank Accounts"] // 3
]我想编写一个C#方法,它使用Json.NET返回包含特定字符串的数组的索引。例如,如果我通过Bank Accounts,那么它将返回3。
我试图使用以下代码:
public byte GetIndex(JArray array, string category)
{
JArray.IndexOf(array.Descendants().Where(p => p.Contains(category)));
}但是与JObject不同,JArray不包含Descendants()方法,我甚至不确定lambda表达式是否真的表达了我想要实现的目标。
如何做到这一点?
发布于 2018-11-11 10:42:46
用JContainer.DescendantsAndSelf()和JToken代替
var root = (JContainer)JToken.Parse(content);
var descendant = "Addresses";
var query = root
// Recursively descend the JSON hierarchy
.DescendantsAndSelf()
// Select all properties named descendant
.OfType<JProperty>()
.Where(p => p.Name == descendant)
// Select their value
.Select(p => p.Value)
// And filter for those that are arrays.
.OfType<JArray>();或者没有JContainer.DescendantsAndSelf()
var root = JToken.Parse(content);
var descendant = "Addresses";
var query = root
// Recursively descend the JSON hierarchy using the JSONpath recursive descent operator "..", and select the values of all properties named descendant
.SelectTokens(string.Format("..{0}", descendant))
// And filter for those that are arrays.
.OfType<JArray>();https://stackoverflow.com/questions/53247826
复制相似问题