如何在反序列化时设置某些 属性 的值?

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;
        }
    }
}