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



我有一个类的属性,设置依赖于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;
}
}
}

相关内容

  • 没有找到相关文章

最新更新