using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
static IEnumerable<string> GetJson()
""key1"": ""value1 value"",
""key1"": ""value1 value"",
public static void Test()
foreach (var json in GetJson())
Console.WriteLine("Testing: ");
TestExtensionMethod(json);
public static void TestExtensionMethod(string json)
var jsonfile = JToken.Parse(json);
var child = jsonfile["parent"].SingleOrArrayItems().FirstOrDefault();
var value1 = child == null ? null : child.SelectToken("child.key1");
Console.WriteLine("Result of extension method:");
Console.WriteLine(value1);
public static void TestSelectTokens(string json)
var jsonfile = JToken.Parse(json);
var value1 = jsonfile.SelectTokens("parent..child.key1").FirstOrDefault();
Console.WriteLine("Result of SelectTokens:");
Console.WriteLine(value1);
public static class JsonExtensions
public static IEnumerable<JToken> SingleOrArrayItems(this JToken source)
if (source == null || source.Type == JTokenType.Null)
return Enumerable.Empty<JToken>();
IEnumerable<JToken> arr = source as JArray;
return arr ?? new[] { source };
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);