有一些非基于属性的方法在序列化时忽略所有没有相应构造函数参数的属性吗?例如,在序列化此类时,Combo
应忽略属性。实例的往返序列化/反序列化MyClass
不需要Combo
序列化。理想情况下,我可以使用一些现成的设置。
public class MyClass
{
public MyClass(int myInt, string myString)
{
this.MyInt = myInt;
this.MyString = myString;
}
public int MyInt { get; }
public string MyString { get; }
public string Combo => this.MyInt + this.MyString;
}
您可以使用自定义IContractResolver
方式进行此操作:
public class ConstructorPropertiesOnlyContractResolver : DefaultContractResolver
{
readonly bool serializeAllWritableProperties;
public ConstructorPropertiesOnlyContractResolver(bool serializeAllWritableProperties)
: base()
{
this.serializeAllWritableProperties = serializeAllWritableProperties;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
if (contract.CreatorParameters.Count > 0)
{
foreach (var property in contract.Properties)
{
if (contract.CreatorParameters.GetClosestMatchProperty(property.PropertyName) == null)
{
if (!serializeAllWritableProperties || !property.Writable)
property.Readable = false;
}
}
}
return contract;
}
}
然后像这样使用它:
var settings = new JsonSerializerSettings { ContractResolver = new ConstructorPropertiesOnlyContractResolver(false) };
var json = JsonConvert.SerializeObject(myClass, Formatting.Indented, settings );
通过true
对serializeAllWritableProperties
,如果你也想不包含在构造函数中的参数列表,如序列化的读/写性能AnUnrelatedReadWriteProperty
在:
public class MyClass
{
public MyClass(int myInt, string myString)
{
this.MyInt = myInt;
this.MyString = myString;
}
public int MyInt { get; private set; }
public string MyString { get; private set; }
public string Combo { get { return this.MyInt + this.MyString; } }
public string AnUnrelatedReadWriteProperty { get; set; }
}
请注意,您可能需要缓存合同解析器以获得最佳性能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句