user3310334
user3310334

Reputation:

JsonConvert don't include unset numeric members in serialization

I have a class

public class Container
{
    public long Id { get; set; }
    public string Name { get; set; }
    public List<string> Aliases { get; set; }
    public double Height { get; set; }
    public double Weight { get; set; }
}

if I create

var container = new Container
{
    Weight = 127.3
}

I want it serialised to the JSON:

{
  "Weight": 127.3
}

but actually it gets serialized to this:

{
  "Id": 0,
  "Height": 0.0,
  "Weight": 127.3
}

I am trying to use this to serialize it:

var settings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    MissingMemberHandling = MissingMemberHandling.Ignore
};
var json = JsonConvert.SerializeObject(container, Formatting.Indented, settings);

Primitive types (like int and long I guess) can't be null as far as I'm aware. I think that's what causes this unintended behaviour.

How can I fix this though to get the output I want when I haven't explicitly set the values? I think turning all long into Nullable<long> for example might not be ideal.

Upvotes: 0

Views: 97

Answers (1)

djsoteric
djsoteric

Reputation: 316

Those values are not nullable so they will never be null. The reason you don't see your string property printed is because strings are nullable so their default value is null. Numeric types like int, long, etc. have default values of 0, 0.0, etc. If you truly want to ignore default values, you need to use DefaultValueHandling instead. I would normally just make those properties nullable (e.g., int? MyNullableInt) as I truly don't care about nulls, but some items may truly have a value of 0 that I need to know about.

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm

Upvotes: 2

Related Questions