c# - 如何在使用 Newtonsoft.Json 序列化 json 时忽略默认值

标签 c# json json.net

我正在使用 Newtonsoft.Json.JsonConvertTextbox (WinForms) 序列化为 json,我希望序列化跳过具有默认值或空数组的属性。

我尝试在 JsonSerializerSettings 中使用 NullValueHandling = NullValueHandling.Ignore 但似乎没有任何影响。

这是完整的代码示例(已简化):

JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.None,
                    DefaultValueHandling = DefaultValueHandling.Ignore,
                    NullValueHandling = NullValueHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ObjectCreationHandling = ObjectCreationHandling.Replace,
                    PreserveReferencesHandling = PreserveReferencesHandling.None,
                    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                };

    string json = JsonConvert.SerializeObject(textbox, settings);

有什么想法吗?

最佳答案

您可以使用标准的条件序列化模式:

private int bar = 6; // default value of 6
public int Bar { get { return bar;} set { bar = value;}}
public bool ShouldSerializeBar()
{
    return Bar != 6;
}

关键是 public bool ShouldSerialize*() 方法,其中 * 是成员名称。 XmlSerializer、protobuf-net、PropertyDescriptor 等也使用了这种模式。

当然,这确实意味着您需要访问该类型。

关于c# - 如何在使用 Newtonsoft.Json 序列化 json 时忽略默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11628353/

相关文章:

c# - JSON.net反序列化对象嵌套数据

c# - JSON.NET 中的条件输出处理

c# - 使 Entity Framework 将存储过程结果集列解释为 bool 而不是 int?

c# - 无法从字符串转换为 System.Diagnostics.ProcessStartInfo C#

json - 我应该在 VS Code 中为 'json.maxItemsComputed' 设置什么?

java - 如何在 Android Studio 中以半径显示 2 个标记的显示距离

c# - Newtonsoft JSON - 动态对象

c# - Localhost 和 request.Url.Authority

c# - Excel 互操作 - 如何停止数字(存储为文本)为 "evaluated"

c# - JsonConvert.DeserializeObject 到 en-US 文化