[英]How to set value of certain property on deserialization?
我有一个 class,其属性设置器依赖于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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.