我有一个类的属性,设置依赖于VeryImportantProperty
。但是属性不应该按照设计序列化。
,我接收JSON时,必须设置VeryImportantProperty
之前在反序列化和设置其他属性。
我想可以通过修改ContractResolver
来完成。我为VeryImportantProperty
存储值,但我不知道如何分配它
我尝试使用以下ContractResolver
,但它不影响
public class MyContractResolver : DefaultContractResolver
{
public VeryImportantClass VeryImportantPropertyValue { get; set; }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName == "VeryImportantProperty" && VeryImportantPropertyValue != null)
{
property.DefaultValue = VeryImportantPropertyValue;
property.DefaultValueHandling = DefaultValueHandling.Populate;
property.Order = -1;
}
return property;
}
}
我通过创建覆盖CreateContract
的ContractResolver
来解决这个问题,将Converter
设置为覆盖Create
的自定义VeryImportantProperty
传递给构造函数
代码:
public class MyContractResolver : DefaultContractResolver
{
public VeryImportantClass VeryImportantPropertyValue { get; set; }
protected override JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);
if (VeryImportantPropertyValue == null)
return contract;
// Solution for multiple classes is commented
if (objectType == typeof(ContainerClass)/* || objectType.IsSubclassOf(typeof(BaseContainer))*/)
{
contract.Converter = new ImportantClassConverter(VeryImportantPropertyValue);
}
return contract;
}
private class ImportantClassConverter: CustomCreationConverter<VeryImportantClass>
{
public EntityConverter(VeryImportantClass veryImportantPropertyValue)
{
_veryImportantPropertyValue= veryImportantPropertyValue;
}
private readonly VeryImportantClass _veryImportantPropertyValue;
public override VeryImportantClass Create(Type objectType)
{
// Might be simplified but it was used for multiple container classes with one parent
return objectType.GetConstructor(new[] { typeof(ContainerClass) })
?.Invoke(new[] { _veryImportantPropertyValue }) as ContainerClass;
}
}
}