简体   繁体   中英

default double value handling in JsonConvert.SerializeObject

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 )?

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; }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM