在JArray中进行深度搜索

时间:2018-11-11 10:26:41

标签: c# json json.net

我有以下JSON。

[
    ["Identity"], // 0
    ["Contact Information"], // 1
    ["Service Fields"], // 2
    ["Addresses", "Bank Accounts"] // 3
]

我想编写一个使用Json.NET返回包含特定字符串的数组的索引的C#方法。例如,如果我通过Bank Accounts,则它将返回3

我尝试使用以下代码:

public byte GetIndex(JArray array, string category)
{
    JArray.IndexOf(array.Descendants().Where(p => p.Contains(category)));
}

但与JObject不同的是,JArray不包含Descendants()方法,而且我甚至不确定我的lambda表达式是否真正表达了我想要实现的目标。

如何实现?

1 个答案:

答案 0 :(得分:0)

改为使用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>();