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 ?
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.
Yes, add prop. PropertyName = prop. UnderlyingName; inside the loop in the resolver. This will cause the property to use its original name.
Newtonsoft. Json package is not provided by RestSharp, is marked as obsolete on NuGet, and no longer supported by its creator.
The exception thrown when an error occurs during JSON serialization or deserialization.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With