Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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 ?

like image 454
Gil Stal Avatar asked Jul 24 '12 09:07

Gil Stal


People also ask

How do I ignore properties in JSON?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

Can I optionally turn off the JsonIgnore attribute at runtime?

Yes, add prop. PropertyName = prop. UnderlyingName; inside the loop in the resolver. This will cause the property to use its original name.

Is Newtonsoft JSON obsolete?

Newtonsoft. Json package is not provided by RestSharp, is marked as obsolete on NuGet, and no longer supported by its creator.

What is a JSON serialization exception?

The exception thrown when an error occurs during JSON serialization or deserialization.


1 Answers

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.

like image 92
Marc Gravell Avatar answered Nov 14 '22 22:11

Marc Gravell