簡體   English   中英

如何在反序列化時設置某些屬性的值?

[英]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;
    }
}

我通過創建覆蓋CreateContractContractResolver來解決這個問題,將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM