using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public List<Child> Children { get; set; } = new List<Child>();
[JsonConverter(typeof(SerializeOnlyJsonConverter))]
public Child FirstChild => Children.First();
public bool ShouldSerializeFirstChild() => Children != null && Children.Count > 0;
public List<GrandChild> Children { get; set; } = new List<GrandChild>();
public string Value { get; set; }
public class SerializeOnlyJsonConverter : JsonConverter
public override bool CanConvert(Type objectType) => throw new NotImplementedException("This converter should only be applied directly to properties");
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
public static void Test()
Children = new List<Child>
Children = new List<GrandChild>
new GrandChild { Value = "I am a grand child" },
var serializedParent = JsonConvert.SerializeObject(parent);
var deserializedParent = JsonConvert.DeserializeObject<Parent>(serializedParent);
var reserializedParent = JsonConvert.SerializeObject(deserializedParent);
Console.WriteLine(serializedParent);
Console.WriteLine(reserializedParent);
Assert.AreEqual(parent.Children[0].Children.Count, deserializedParent.Children[0].Children.Count);
Assert.AreEqual(serializedParent, reserializedParent);
Assert.DoesNotThrow(() => JsonConvert.SerializeObject(new Parent ()));
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("Failed with unhandled exception: ");