[Fork] [Fork] Json.NET Core Template Fiddle V2https://stackoverflow.com/questions/73817932/newtonsoft-json-has-a-deserialization-bug-when-class-has-quick-access-property

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/73817932/newtonsoft-json-has-a-deserialization-bug-when-class-has-quick-access-property

    public class Parent
    {
        public List<Child> Children { get; set; } = new List<Child>();

		[JsonIgnore]
        public Child FirstChild => Children.First();
    }

    public class Child
    {
        public List<GrandChild> Children { get; set; } = new List<GrandChild>();
    }

    public class GrandChild
    {
        public string Value { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            var parent = new Parent
            {
                Children = new List<Child>
                {
                    new Child
                    {
                       Children = new List<GrandChild>
                        {
                            new GrandChild { Value = "I am a grand child" },
                        }
                    },
                    new Child(),
                }
            };

            var serializedParent = JsonConvert.SerializeObject(parent);
            var deserializedParent = JsonConvert.DeserializeObject<Parent>(serializedParent);

            var reserializedParent = JsonConvert.SerializeObject(deserializedParent);
			
			Console.WriteLine(serializedParent);
			Console.WriteLine(reserializedParent);
			
            // Expected: 1, Actual: 2
			Assert.AreEqual(parent.Children[0].Children.Count, deserializedParent.Children[0].Children.Count);
			
			Assert.AreEqual(serializedParent, reserializedParent);
			
			Assert.DoesNotThrow(() => JsonConvert.SerializeObject(new Parent ()));
		}	
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

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