Last active
January 5, 2019 00:34
-
-
Save Dkowald/b0e78c837464e463aded4f7336605db6 to your computer and use it in GitHub Desktop.
Newtonsoft.Json contract resolver to allow non-public property setters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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