[英]Using Json.NET serializer to camel case some properties, but not others
[英]Ignore some of the properties during Json.NET serializing but required on others
我正在使用 Json.Net 序列化 object。 這是代碼:
var jsonText = JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented,
new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
DefaultValueHandling 設置為忽略,因此結果字符串不包含具有默認值的屬性。
在序列化 class 中,無論如何都有一個唯一的屬性應該在結果字符串上,所以我使用一個屬性來確保該屬性存在:
[JsonProperty(PropertyName = "componentMainVersion", Required = Required.Always)]
public ushort Version { get; set; }
問題是該屬性沒有生成到字符串。 將字符串反序列化回 object 時出現異常:
“Newtonsoft.Json.Schema.JsonSchemaException:'object 中缺少必需的屬性:版本...”
如何確保該屬性無論如何都會在結果字符串中(默認值與否)?
試試下面的代碼
[JsonProperty(PropertyName = "componentMainVersion", DefaultValueHandling = DefaultValueHandling.Include)]
public ushort Version { get; set; }
Required 是一個不同的屬性,它確保始終需要該屬性的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.