/questions/46229165/deserialize-objects-from-array-nested-inside-json-response

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

// https://stackoverflow.com/questions/46229165/deserialize-objects-from-array-nested-inside-json-response

	public class Term
	{
		public string Known { get; set; }
		public string Word { get; set; }
	}

    class TestClass
    {
        public static void Test()
		{
        	TestWildcard();
			TestRecursiveDescent();
		}
		
        public static void TestWildcard()
        {
			var responseString = GetJson();
			
			var root = JToken.Parse(responseString);
			var searchTermList = root.SelectTokens("myTerms[*].Term")
				.Select(t => t.ToObject<Term>())
				.ToList();
			
			Console.WriteLine("\nWildcard search result: ");
			Console.WriteLine(JsonConvert.SerializeObject(searchTermList, Formatting.Indented));
		}
		
        public static void TestRecursiveDescent()
		{
			var responseString = GetJson();
			
			var root = JToken.Parse(responseString);
			var searchTermList = root.SelectTokens("..Term")
				.Select(t => t.ToObject<Term>())
				.ToList();
			
			Console.WriteLine("\nRecursive descent search result: ");
			Console.WriteLine(JsonConvert.SerializeObject(searchTermList, Formatting.Indented));
		}
		
		static string GetJson()
		{
			var json = @"{
    ""myName"":""Chris"",
    ""mySpecies"":""Cat"",
    ""myTerms"":
    [
        {
            ""Term"":
            {
                ""Known"":""true"",
                ""Word"":""Meow""
            }
        },
        {
            ""Term"":
            {
                ""Known"":""false"",
                ""Word"":""Bark""
            }
        }
    ]
}";
			return json;
		}
	}


	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
;