Question39335994 Testing for nested keys with Json.NET?

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Data;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Globalization;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
					
	public class Program
	{
		public static void Main()
		{
			var json1 = @"{ ""Key1"" : {""key2"":""value""},  ""key3"" : ""other values"" }";

			TestJson(json1, "Key1.key2");
			
			var json2 = @"{ ""Key1"" : [{""NoKey2"":""value""}, {""key2"":""value""}],  ""key3"" : ""other values"" }";
			
			TestJson(json2, "Key1[*].key2");
		}
		
		static void TestJson(string json, string query)
		{
			Console.WriteLine("Testing JSON: ");
			Console.WriteLine(json);
			Console.WriteLine("Testing query: ");
			Console.WriteLine(query);
			
			var globalEventStream = new [] 
			{ 
				new { EventArgs = new { Data = json } }, 
				new { EventArgs = new { Data = @"{""key5"": ""some other random json that should not appear in the query"" }" } } 
			};

			var valueQuery = globalEventStream
				.Select(e => JObject.Parse(e.EventArgs.Data))
				.Where(o => o.SelectTokens(query).Any());

			Console.WriteLine("Results of running the query: ");			
			Console.WriteLine(JsonConvert.SerializeObject(valueQuery, Formatting.Indented));
		}
	}
;