Skip to content

Instantly share code, notes, and snippets.

@Dkowald
Last active January 5, 2019 00:34
Show Gist options
  • Save Dkowald/b0e78c837464e463aded4f7336605db6 to your computer and use it in GitHub Desktop.
Save Dkowald/b0e78c837464e463aded4f7336605db6 to your computer and use it in GitHub Desktop.
Newtonsoft.Json contract resolver to allow non-public property setters.
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
// ReSharper disable once CheckNamespace
namespace kwd.gist
{
/// <summary>
/// Support serialize properties with non-public setters
/// </summary>
public class PrivateSetterContractResolver : DefaultContractResolver
{
/// <summary>
/// Extend base to allow writes for non-public property setter
/// </summary>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var jProperty = base.CreateProperty(member, memberSerialization);
if (jProperty.Writable) { return jProperty; }
if(member is PropertyInfo propertyInfo) { jProperty.Writable = propertyInfo.GetSetMethod(true) != null; }
return jProperty;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment