使用Json.NET进行序列化时如何忽略空集合 [英] How to omit empty collections when serializing with Json.NET

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

问题描述

我正在使用Newtonsoft的Json.NET 7.0.0.0将类从C#序列化为JSON:

I'm using Newtonsoft's Json.NET 7.0.0.0 to serialize classes to JSON from C#:

class Foo
{
    public string X;
    public List<string> Y = new List<string>();
}

var json =
    JsonConvert.SerializeObject(
        new Foo(),
        Formatting.Indented,
        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

这里json的值是

{ "Y": [] }

但是如果Y是一个空列表,我希望它是{ }.

but I would like it to be { } if Y is an empty list.

我找不到令人满意的方法来实现这一目标.也许使用自定义合同解析器?

I couldn't find a satisfactory way to achieve this. Maybe with a custom contract resolver?

推荐答案

如果您正在寻找一种可以在不同类型上通用且不需要任何修改(属性等)的解决方案,那么最好的解决方案是我可以考虑是否将是一个自定义的DefaultContractResolver类.它将使用反射来确定给定类型的任何IEnumerable是否为空.

If you're looking for a solution which can be used generically across different types and does not require any modification (attributes, etc), then the best solution that I can think if would be a custom DefaultContractResolver class. It would use reflection to determine if any IEnumerables for a given type are empty.

public class IgnoreEmptyEnumerablesResolver : DefaultContractResolver
{
    public static readonly IgnoreEmptyEnumerablesResolver Instance = new IgnoreEmptyEnumerablesResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property.PropertyType != typeof(string) &&
            typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
        {
            property.ShouldSerialize = instance =>
            {
                IEnumerable enumerable = null;

                // this value could be in a public field or public property
                switch (member.MemberType)
                {
                    case MemberTypes.Property:
                        enumerable = instance
                            .GetType()
                            .GetProperty(member.Name)
                            .GetValue(instance, null) as IEnumerable;
                        break;
                    case MemberTypes.Field:
                        enumerable = instance
                            .GetType()
                            .GetField(member.Name)
                            .GetValue(instance) as IEnumerable;
                        break;
                    default:
                        break;

                }

                if (enumerable != null)
                {
                    // check to see if there is at least one item in the Enumerable
                    return enumerable.GetEnumerator().MoveNext();
                }
                else
                {
                    // if the list is null, we defer the decision to NullValueHandling
                    return true;
                }

            };
        }

        return property;
    }
}

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

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