questions/48156055/how-take-this-json-path-in-newtonsoft-json-c-sharp

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 System.Globalization;


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

// https://stackoverflow.com/questions/48156055/how-take-this-json-path-in-newtonsoft-json-c-sharp


    class TestClass
    {
        public static void Test()
        {
            string content = GetJson();

            var jo = JObject.Parse(content);

            var jsonPath = "$..Data[*]";
            var result = jo.SelectTokens(jsonPath, true /* to get error when it is not found */ )
                .Select(o => o.ToObject<Dictionary<string, object>>())
                .ToList();

			Console.WriteLine("\nRe-serialized {0}:", result);
            Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
        }

        static string GetJson()
        {
            var json = @"{
  ""Foo"": [""Bar""],
  ""Data"": [
    {
      ""Code"": ""625087"",
      ""Name"": ""Customer Name"",
      ""Email"": ""[email protected]""
    },
    {
      ""Code"": ""625087"",
      ""Name"": ""Customer Name"",
      ""Email"": ""[email protected]""
    },
    {
      ""Code"": ""625087"",
      ""Name"": ""Customer Name"",
      ""Email"": ""[email protected]""
    }
  ],

}";
          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");
        }
    }
;