C# 如何避免序列化默认值?
我应该如何标记属性,如果属性具有默认值,则它们不应序列化?例如,如果我有布尔值,那么它应该被序列化,如果仅设置为true,则与可为null的值相同,如果它们为null,则我不希望将它们包含在序列化文件中。有指定属性这样的东西。我找不到关于它的msdn文档,但应该会有帮助。 基本上,你必须这样写:C# 如何避免序列化默认值?,c#,C#,我应该如何标记属性,如果属性具有默认值,则它们不应序列化?例如,如果我有布尔值,那么它应该被序列化,如果仅设置为true,则与可为null的值相同,如果它们为null,则我不希望将它们包含在序列化文件中。有指定属性这样的东西。我找不到关于它的msdn文档,但应该会有帮助。 基本上,你必须这样写: //this property would not be serialized if it contains String.Empty value public string PropertyName
//this property would not be serialized if it contains String.Empty value
public string PropertyName { get; set; }
[XmlIgnore]
public bool PropertyNameSpecified
{
get { return PropertyName != String.Empty; }
}
public class Person {
public string Name {get;set;}
[DefaultValue(true)]
public bool IsAdult {get;set;} = true
}
好的,我自己找到的。它是
[DefaultValue(false)]
。如果我用这个属性标记某个属性,那么只有当它与()中的值不同时,它才会被序列化
科森科夫的回答让我走上了正确的道路。在我的例子中,我想让bool默认为true,即使它是否反序列化。我的结局是这样的:
//this property would not be serialized if it contains String.Empty value
public string PropertyName { get; set; }
[XmlIgnore]
public bool PropertyNameSpecified
{
get { return PropertyName != String.Empty; }
}
public class Person {
public string Name {get;set;}
[DefaultValue(true)]
public bool IsAdult {get;set;} = true
}
所以这个Json
{"Name" :"SomePerson"}
结果进入这个对象
{ Name : "SomePerson", IsAdult : true}
解释:
- 默认值属性告诉序列化程序默认值是什么。因此,如果序列化程序重写当前值或不重写当前值,它只会影响决策,因为它与提供的值或默认值不匹配
- =true设置初始值
- 您仍然必须提供初始值,因为序列化程序不会触及IsAdult属性,但在系统默认情况下bool为false