Fundamentally, I want to include or omit a property from the generated Json based on its value at the time of serialization.
More-specifically, I have a type that knows
Ok, after digging around in Json.NET source for a while, I finally got this working and it will even honor the ShouldSerialize* and *Specified members that Json.NET supports. Be warned: this is definitely going off into the weeds.
So I realized that the JsonProperty class returned by DefaultContractResolver.CreateProperty has ShouldSerialize and Converter properties, which allow me to specify if the property instance should actually be serialized and, if so, how to do it.
Deserialization requires something a little different, though. DefaultContractResolver.ResolveContract will, by default for a custom type, return a JsonObjectContract with a null Converter property. In order to deserialize my type properly, I needed to set the Converter property when the contract is for my type.
Here's the code (with error handling / etc removed to keep things as small as possible).
First, the type that needs special handling:
public struct Optional
{
public readonly bool ValueProvided;
public readonly T Value;
private Optional( T value )
{
this.ValueProvided = true;
this.Value = value;
}
public static implicit operator Optional( T value )
{
return new Optional( value );
}
}
And there's the converter that will serialize it properly after we know it should be serialized:
public class OptionalJsonConverter : JsonConverter
{
public static OptionalJsonConverter Instance = new OptionalJsonConverter();
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
var optional = (Optional)value; // Cast so we can access the Optional members
serializer.Serialize( writer, optional.Value );
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer )
{
var valueType = objectType.GetGenericArguments()[ 0 ];
var innerValue = (T)serializer.Deserialize( reader, valueType );
return (Optional)innerValue; // Explicitly invoke the conversion from T to Optional
}
public override bool CanConvert( Type objectType )
{
return objectType == typeof( Optional );
}
}
Finally, and most-verbosely, here's the ContractResolver that inserts the hooks:
public class CustomContractResolver : DefaultContractResolver
{
// For deserialization. Detect when the type is being deserialized and set the converter for it.
public override JsonContract ResolveContract( Type type )
{
var contract = base.ResolveContract( type );
if( contract.Converter == null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof( Optional<> ) )
{
// This may look fancy but it's just calling GetOptionalJsonConverter with the correct T
var optionalValueType = type.GetGenericArguments()[ 0 ];
var genericMethod = this.GetAndMakeGenericMethod( "GetOptionalJsonConverter", optionalValueType );
var converter = (JsonConverter)genericMethod.Invoke( null, null );
// Set the converter for the type
contract.Converter = converter;
}
return contract;
}
public static OptionalJsonConverter GetOptionalJsonConverter()
{
return OptionalJsonConverter.Instance;
}
// For serialization. Detect when we're creating a JsonProperty for an Optional member and modify it accordingly.
protected override JsonProperty CreateProperty( MemberInfo member, MemberSerialization memberSerialization )
{
var jsonProperty = base.CreateProperty( member, memberSerialization );
var type = jsonProperty.PropertyType;
if( type.IsGenericType && type.GetGenericTypeDefinition() == typeof( Optional<> ) )
{
// This may look fancy but it's just calling SetJsonPropertyValuesForOptionalMember with the correct T
var optionalValueType = type.GetGenericArguments()[ 0 ];
var genericMethod = this.GetAndMakeGenericMethod( "SetJsonPropertyValuesForOptionalMember", optionalValueType );
genericMethod.Invoke( null, new object[]{ member.Name, jsonProperty } );
}
return jsonProperty;
}
public static void SetJsonPropertyValuesForOptionalMember( string memberName, JsonProperty jsonProperty )
{
if( jsonProperty.ShouldSerialize == null ) // Honor ShouldSerialize*
{
jsonProperty.ShouldSerialize =
( declaringObject ) =>
{
if( jsonProperty.GetIsSpecified != null && jsonProperty.GetIsSpecified( declaringObject ) ) // Honor *Specified
{
return true;
}
object optionalValue;
if( !TryGetPropertyValue( declaringObject, memberName, out optionalValue ) &&
!TryGetFieldValue( declaringObject, memberName, out optionalValue ) )
{
throw new InvalidOperationException( "Better error message here" );
}
return ( (Optional)optionalValue ).ValueProvided;
};
}
if( jsonProperty.Converter == null )
{
jsonProperty.Converter = CustomContractResolver.GetOptionalJsonConverter();
}
}
// Utility methods used in this class
private MethodInfo GetAndMakeGenericMethod( string methodName, params Type[] typeArguments )
{
var method = this.GetType().GetMethod( methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static );
return method.MakeGenericMethod( typeArguments );
}
private static bool TryGetPropertyValue( object declaringObject, string propertyName, out object value )
{
var propertyInfo = declaringObject.GetType().GetProperty( propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
if( propertyInfo == null )
{
value = null;
return false;
}
value = propertyInfo.GetValue( declaringObject, BindingFlags.GetProperty, null, null, null );
return true;
}
private static bool TryGetFieldValue( object declaringObject, string fieldName, out object value )
{
var fieldInfo = declaringObject.GetType().GetField( fieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
if( fieldInfo == null )
{
value = null;
return false;
}
value = fieldInfo.GetValue( declaringObject );
return true;
}
}
I hope that helps somebody else. Feel free to ask questions if anything is unclear or if it looks like I missed something.