好的,在 Json.NET 源代码中挖掘了一段时间后,我终于得到了这个工作,它甚至会尊重 Json.NET 支持的 ShouldSerialize* 和 *Specified 成员。请注意:这肯定会变成杂草。
所以我意识到 DefaultContractResolver.CreateProperty 返回的 JsonProperty 类具有 ShouldSerialize 和 Converter 属性,这允许我指定属性实例是否应该实际序列化,如果是,如何执行。
不过,反序列化需要一些不同的东西。DefaultContractResolver.ResolveContract 默认情况下,对于自定义类型,将返回一个带有 null Converter 属性的 JsonObjectContract。为了正确反序列化我的类型,当合同适用于我的类型时,我需要设置 Converter 属性。
这是代码(删除了错误处理/等以使事情尽可能小)。
一、需要特殊处理的类型:
public struct Optional<T>
{
public readonly bool ValueProvided;
public readonly T Value;
private Optional( T value )
{
this.ValueProvided = true;
this.Value = value;
}
public static implicit operator Optional<T>( T value )
{
return new Optional<T>( value );
}
}
在我们知道它应该被序列化之后,有一个转换器会正确地序列化它:
public class OptionalJsonConverter<T> : JsonConverter
{
public static OptionalJsonConverter<T> Instance = new OptionalJsonConverter<T>();
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer )
{
var optional = (Optional<T>)value; // Cast so we can access the Optional<T> 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<T>)innerValue; // Explicitly invoke the conversion from T to Optional<T>
}
public override bool CanConvert( Type objectType )
{
return objectType == typeof( Optional<T> );
}
}
最后,也是最冗长的,这里是插入钩子的 ContractResolver:
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<T> 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<T> GetOptionalJsonConverter<T>()
{
return OptionalJsonConverter<T>.Instance;
}
// For serialization. Detect when we're creating a JsonProperty for an Optional<T> 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<T> 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<T>( 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<T>)optionalValue ).ValueProvided;
};
}
if( jsonProperty.Converter == null )
{
jsonProperty.Converter = CustomContractResolver.GetOptionalJsonConverter<T>();
}
}
// 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;
}
}
我希望这对其他人有所帮助。如果有任何不清楚的地方或者看起来我错过了什么,请随时提出问题。