Json.net DefaultValueHandling exempting boolean alone

前端 未结 1 2043
夕颜
夕颜 2020-12-11 17:49

While serializing using json.net i used DefaultValueHandling.Ignore in serialization settings, which result in removal of key if the bool is set false. I want that to be ex

相关标签:
1条回答
  • 2020-12-11 18:35

    DefaultValueHandling.Ignore in serialization settings can be overridden by decorating any property with [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)] attribute. Here is the class:

    public class Person
    {
        public string FirstName { get; set; }
    
        public string LastName { get; set; }
    
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
        public bool IsEmployed { get; set; }
    }
    

    Lets say that we have the following sample:

    var person = new Person
                {
                    FirstName = "John",
                    IsEmployed = false
                };
    
    var json = JsonConvert.SerializeObject(person, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
    

    Will result in following json:

    {
        "FirstName": "John",
        "IsEmployed": false
    }
    
    0 讨论(0)
提交回复
热议问题