Json.net DefaultValueHandling 单独排除布尔值

Json.net DefaultValueHandling exempting boolean alone(Json.net DefaultValueHandling 单独排除布尔值)

本文介绍了Json.net DefaultValueHandling 单独排除布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 json.net 进行序列化时,我在序列化设置中使用了 DefaultValueHandling.Ignore,如果 bool 设置为 false,则会导致删除键.我希望仅对 bool 类型豁免,并申请其他类型和类.请帮忙

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

提前致谢.

推荐答案

DefaultValueHandling.Ignore 在序列化设置中可以通过使用 [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include) 装饰任何属性来覆盖] 属性.这是课程:

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

假设我们有以下示例:

var person = new Person
            {
                FirstName = "John",
                IsEmployed = false
            };

var json = JsonConvert.SerializeObject(person, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

将产生以下 json:

Will result in following json:

{
    "FirstName": "John",
    "IsEmployed": false
}

这篇关于Json.net DefaultValueHandling 单独排除布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Json.net DefaultValueHandling 单独排除布尔值

基础教程推荐