using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
public static void Main()
var test = new MyTestObject();
var settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();
settings.Formatting = Formatting.Indented;
var json = JsonConvert.SerializeObject(test, settings);
[SerializeOnly("TestValue1")]
[SerializeOnly("TestValue3")]
public ComplexTestObject Property1 { get; set; }
[SerializeOnly("TestValue2")]
public ComplexTestObject Property2 { get; set; }
Property1 = new ComplexTestObject();
Property2 = new ComplexTestObject();
public string TestValue1 { get; set; }
public string TestValue2 { get; set; }
public string TestValue3 { get; set; }
public ComplexTestObject()
class CustomResolver : DefaultContractResolver
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in props)
if (!prop.PropertyType.IsPrimitive && prop.PropertyType != typeof(string))
PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
if (pi != null && pi.CanRead)
var childPropertiesToSerialize = pi.GetCustomAttributes<SerializeOnly>()
.Select(att => att.PropertyName);
if (childPropertiesToSerialize.Any())
prop.Converter = new CustomConverter(childPropertiesToSerialize);
class CustomConverter : JsonConverter
private HashSet<string> propertiesToSerialize;
public CustomConverter(IEnumerable<string> propertiesToSerialize)
this.propertiesToSerialize = new HashSet<string>(propertiesToSerialize);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
writer.WriteStartObject();
foreach (PropertyInfo prop in value.GetType().GetProperties())
if (prop.CanRead && propertiesToSerialize.Contains(prop.Name))
writer.WritePropertyName(prop.Name);
serializer.Serialize(writer, prop.GetValue(value));
public override bool CanRead
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
throw new NotImplementedException();
public override bool CanConvert(Type objectType)
throw new NotImplementedException();
[AttributeUsage(AttributeTargets.Property, AllowMultiple=true)]
class SerializeOnly : Attribute
public SerializeOnly(string name)
public string PropertyName { get; set; }