How to ignore default values while serializing json with Newtonsoft.Json

c#, json, json.net

Solution

You could use the standard conditional-serialization pattern:

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 a `public bool ShouldSerialize*()` method, where `*` is the member-name. This pattern is also used by `XmlSerializer`, protobuf-net, `PropertyDescriptor`, etc.

This does, of course, mean you need access to the type.

Problem

I'm using `Newtonsoft.Json.JsonConvert` to serialize a `Textbox` (WinForms) into json and I want the serialization to skip properties with default values or empty arrays. I'v tried to use `NullValueHandling = NullValueHandling.Ignore` in `JsonSerializerSettings` but is doesn't seem to affect anything. Here is the full code sample (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 ?

Original source