Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set DefaultValue for Color using JSON.Net

Tags:

json

c#

json.net

With the following Test class

public class Test {
    [DefaultValue("Black")] 
    public Color ForeColor = Color.Black;
}

And the following serialization code:

var test = new Test();
var json = JsonConvert.SerializeObject(test, Newtonsoft.Json.Formatting.None,
    new JsonSerializerSettings {
        NullValueHandling = NullValueHandling.Ignore,
        DefaultValueHandling = DefaultValueHandling.Ignore
});

I get

{"ForeColor":"Black"}

Is there a (simple) way to have a Color property not serialized if it's the same as a specified default value.

like image 783
Brad Patton Avatar asked Dec 11 '25 03:12

Brad Patton


1 Answers

The default values stored in the DefaultValueAttribute are specific to their type. So if you specify a default value of "Black", then the default value is an actual string even though the property type is of a different type.

In order to work with other non-simple types, you have to use a special overload of the attribute and specify the object type and a string value that can be converted into the target type using a known type converter.

Luckily, the Color struct does have a type converter registered. So you can use it like this:

public class Test
{
    [DefaultValue(typeof(Color), "Black")]
    public Color ForeColor = Color.Black;
}

And then it works as desired:

var test = new Test();
var json = JsonConvert.SerializeObject(test, new JsonSerializerSettings {
    DefaultValueHandling = DefaultValueHandling.Ignore
});
Console.WriteLine(json); // {}
like image 91
poke Avatar answered Dec 13 '25 16:12

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!