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>();
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; }
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = false)]
public class GetOnlyJsonPropertyAttribute : Attribute
public class GetOnlyContractResolver : DefaultContractResolver
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
var property = base.CreateProperty(member, memberSerialization);
var attributes = property.AttributeProvider.GetAttributes(typeof(GetOnlyJsonPropertyAttribute), true);
if (attributes != null && attributes.Count > 0)
property.ShouldDeserialize = (a) => false;
public static void Test()
Children = new List<Child>
Children = new List<GrandChild>
new GrandChild { Value = "I am a grand child" },
IContractResolver resolver = new GetOnlyContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = resolver };
var serializedParent = JsonConvert.SerializeObject(parent, settings);
var deserializedParent = JsonConvert.DeserializeObject<Parent>(serializedParent, settings);
var reserializedParent = JsonConvert.SerializeObject(deserializedParent, settings);
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 (), settings));
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: ");