C# 在Json.NET序列化期间忽略某些属性,但在其他属性上是必需的
我正在使用Json.Net序列化一个对象。 代码如下:C# 在Json.NET序列化期间忽略某些属性,但在其他属性上是必需的,c#,json,serialization,json.net,C#,Json,Serialization,Json.net,我正在使用Json.Net序列化一个对象。 代码如下: var jsonText = JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); DefaultValueHandling设置为忽略,因此结果字符串
var jsonText = JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
DefaultValueHandling设置为忽略,因此结果字符串不包含具有默认值的属性
在序列化类中,有一个唯一的属性无论如何都应该位于结果字符串上,
因此,我使用一个属性来确保属性将在那里:
[JsonProperty(PropertyName = "componentMainVersion", Required = Required.Always)]
public ushort Version { get; set; }
问题是属性没有生成到字符串中。
将字符串反序列化回对象时出现异常:
“Newtonsoft.Json.Schema.JsonSchemaException:'所需属性为
对象中缺少:版本…”
如何确保该属性仍在结果字符串中(默认值与否)?请尝试以下代码
[JsonProperty(PropertyName = "componentMainVersion", DefaultValueHandling = DefaultValueHandling.Include)]
public ushort Version { get; set; }
Required是另一个属性,它确保始终需要该属性的值