使用Newtonsoft.Json序列化json时如何忽略默认值 [英] How to ignore default values while serializing json with Newtonsoft.Json

查看:178
本文介绍了使用Newtonsoft.Json序列化json时如何忽略默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Newtonsoft.Json.JsonConvert to serialize a Textbox (WinForms) into json and I want the serialization to skip properties with default values or empty arrays.

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

I'v tried to use NullValueHandling = NullValueHandling.Ignore in JsonSerializerSettings but is doesn't seem to affect anything.

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

Here is the full code sample (simplified):

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

有什么想法吗?

推荐答案

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

You could use the standard conditional-serialization pattern:

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 等也使用此模式.

The key is a public bool ShouldSerialize*() method, where * is the member-name. This pattern is also used by XmlSerializer, protobuf-net, PropertyDescriptor, etc.

这当然意味着您需要访问该类型.

This does, of course, mean you need access to the type.

这篇关于使用Newtonsoft.Json序列化json时如何忽略默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆