Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 exempted for type bool alone, and apply for other types and classes. Please help

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
214 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...