Skip to content

Instantly share code, notes, and snippets.

@gbiellem
Created January 25, 2019 00:12
Show Gist options
  • Save gbiellem/706ae99913ae42baabfc8682f64c6fb0 to your computer and use it in GitHub Desktop.
Save gbiellem/706ae99913ae42baabfc8682f64c6fb0 to your computer and use it in GitHub Desktop.
JTokenExtensions for Json.Net
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