Created
January 25, 2019 00:12
-
-
Save gbiellem/706ae99913ae42baabfc8682f64c6fb0 to your computer and use it in GitHub Desktop.
JTokenExtensions for Json.Net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Newtonsoft.Json.Linq; | |
public static class JTokenExtensions | |
{ | |
public static List<JToken> FindTokens(this JToken containerToken, string name, StringComparison stringComparision = StringComparison.Ordinal) | |
{ | |
var matches = new List<JToken>(); | |
FindTokens(containerToken, name, matches, stringComparision); | |
return matches; | |
} | |
static void FindTokens(JToken containerToken, string name, ICollection<JToken> matches, StringComparison stringComparision) | |
{ | |
if (containerToken.Type == JTokenType.Object) | |
{ | |
foreach (var child in containerToken.Children<JProperty>()) | |
{ | |
if (string.Equals(child.Name, name, stringComparision)) | |
{ | |
matches.Add(child.Value); | |
} | |
FindTokens(child.Value, name, matches, stringComparision); | |
} | |
} | |
else if (containerToken.Type == JTokenType.Array) | |
{ | |
foreach (var child in containerToken.Children()) | |
{ | |
FindTokens(child, name, matches, stringComparision); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment