[英]How to ignore default values while serializing json with Newtonsoft.Json
我正在使用Newtonsoft.Json.JsonConvert
將Textbox
(WinForms)序列化為json,我希望序列化跳過具有默認值或空數組的屬性。
我試圖在JsonSerializerSettings
使用NullValueHandling = NullValueHandling.Ignore
,但似乎沒有任何影響。
這是完整的代碼示例(簡化):
JsonSerializerSettings settings = new JsonSerializerSettings()
{
Formatting = Formatting.None,
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Replace,
PreserveReferencesHandling = PreserveReferencesHandling.None,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
};
string json = JsonConvert.SerializeObject(textbox, settings);
有任何想法嗎 ?
您可以使用標准條件序列化模式:
private int bar = 6; // default value of 6
public int Bar { get { return bar;} set { bar = value;}}
public bool ShouldSerializeBar()
{
return Bar != 6;
}
關鍵是public bool ShouldSerialize*()
方法,其中*
是成員名。 XmlSerializer
,protobuf-net, PropertyDescriptor
等也使用此模式。
當然,這確實意味着您需要訪問該類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.