[英]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.