Reputation: 15128
I'm using Newtonsoft.Json
in order to serialize a custom class and I have an issue how the library handles the default values for doubles.
The class can be like:
class Person
{
public string FullName { get; set; }
public double Score {get; set; }
public bool IsStudent {get; set; }
public double Weight {get;set; }
}
where FullName
and Score
are required fields and IsStudent
is an optional field.
If I serialize the object:
Person mark = new Person();
mark.FullName = "Mark Twain";
mark.Score = 0.0;
var jsonMark = JsonConvert.SerializeObject(mark);
what I get is
{
"FullName": "Mark Twain";
}
because 0.0 is the default for double
.
I need to pass that value always, also if it's 0.0
. If I serialize with JsonSerializerSettings
var settings = new JsonSerializerSettings();
settings.DefaultValueHandling = DefaultValueHandling.Include;
var jsonMark = JsonConvert.SerializeObject(mark);
I get
{
"FullName": "Mark Twain",
"Score": 0.0,
"IsStudent": false,
"Weight": 0.0
}
so all properties (in this demo IsStudent
and Weight
) that I didn't set. In my original code the class contains other double
and boolean
fields and to the API I don't need to include them (if I pass Weight
equals to 0 is not a correct value).
There is a way to change the behavior of the serialization to include only specific fields (in my case just Score
but not IsStudent
and Weight
) or at least only a specific type (double
but not bool
)?
Upvotes: 1
Views: 3057
Reputation: 149538
You can decorate those specific properties with the JsonProperty
attribute, and specifically set the DefaultValueHandling
for each one:
class Person
{
public string FullName { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
public double Score { get; set; }
public bool IsStudent { get; set; }
public double Weight { get; set; }
}
Upvotes: 4
Reputation: 2796
Is it what you want?
class Person
{
public string FullName { get; set; }
public double Score {get; set; }
public bool IsStudent {get; set; }
public double? Weight {get;set; }
}
In this case, if you did't set Weight it will be NULL.
Upvotes: 0