How to ignore default values ​​when serializing json with Newtonsoft.Json

I am using Newtonsoft.Json.JsonConvert to serialize Textbox (WinForms) in json, and I want serialization to skip properties with default values ​​or empty arrays.

I'v tried to use NullValueHandling = NullValueHandling.Ignore in JsonSerializerSettings , but nothing seems to be affected.

Here is the complete sample code (simplified):

 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); 

Any ideas?

+6
source share
1 answer

You can use the standard conditional serialization template:

 private int bar = 6; // default value of 6 public int Bar { get { return bar;} set { bar = value;}} public bool ShouldSerializeBar() { return Bar != 6; } 

The key is the public bool ShouldSerialize*() method, where * is the member name. This template is also used by XmlSerializer , protobuf-net, PropertyDescriptor , etc.

This, of course, means you need type access.

+6
source

Source: https://habr.com/ru/post/921189/


All Articles