如果JSON.NET中的值为null或空格,则阻止序列化 [英] Prevent serialization if value is null or whitespace in JSON.NET

查看:229
本文介绍了如果JSON.NET中的值为null或空格,则阻止序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要序列化的对象,使得null和空白"(空或仅空格)值都不会序列化.我不控制对象本身,因此无法设置属性,但是我知道所有属性都是字符串.将NullValueHandling设置为忽略"显然只会使我成为解决方案的一部分.

I have an object that needs to be serialized in such a way that both null and "whitespace" (empty or just spaces) values are not serialized. I don't control the object itself and therefore can't set attributes, but I know that all the properties are strings. Setting NullValueHandling to Ignore obviously only gets me part of the way to the solution.

看来"(据我所知)就像我需要做的是创建自定义DefaultContractResolver,但是我还没有想出可行的解决方案.以下是几次失败的尝试,仅供参考,它们不会引发异常,但对序列化也没有明显的影响:

It "seems" (as best I understand) like what I need to do is create a custom DefaultContractResolver but I haven't come up with a solution that works. Here are a couple failed attempts, for reference, that throw no exceptions but have no obvious effect on the serialization either:

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

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

        /* this doesn't work either
        if (property.ValueProvider.GetValue(member) == null ||
            (property.PropertyType == typeof(string) &&
            string.IsNullOrWhiteSpace((string)property.ValueProvider.GetValue(member))))
        {
            property.ShouldSerialize = i => false;
        }*/

        if (property.PropertyType == typeof(string))
        {
            property.ShouldSerialize =
                instance =>
                {
                    try
                    {
                        string s = (string) instance;
                        bool shouldSkip = string.IsNullOrWhiteSpace(s);
                        return !string.IsNullOrWhiteSpace(s);
                    }
                    catch
                    {
                        return true;
                    }
                };
        }

        return property;
    }
}

我正在通过

string str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
    Formatting = Formatting.None;
    ContractResolver = new NoNullWhiteSpaceResolver();
});

也许我正在朝着这个方向前进,但我感谢人们所提供的任何见解.我通过使用扩展方法/反射来迭代对象的属性,然后将值设置为null(如果它为"nullorwhitespace"),然后使用标准的NullValueHandling,来解决此问题,但我希望我可以找到一个在序列化中配置所有这些的方法.

Maybe I'm going about this backward but I appreciate any insights people have. I've worked around the issue by using an extension method/reflection to iterate over the properties of the object and setting the value to null if it's "nullorwhitespace" and then using the standard NullValueHandling but I'm hoping I can find a way to configure all of this in the serialization.

推荐答案

这似乎可行:

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

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

        if (property.PropertyType == typeof(string)) {
            property.ShouldSerialize =
                instance => {
                    try {
                        var rawValue = property.ValueProvider.GetValue(instance);
                        if (rawValue == null) {
                            return false;
                        }

                        string stringValue = property.ValueProvider.GetValue(instance).ToString();
                        return !string.IsNullOrWhiteSpace(stringValue);
                    }
                    catch {
                        return true;
                    }
                };
        }

        return property;
    }
}

使用此测试类:

public class TestClass {
    public string WhiteSpace => "      ";
    public string Null = null;
    public string Empty = string.Empty;
    public string Value = "value";
}

这是输出:

{"Value":"value"}

这篇关于如果JSON.NET中的值为null或空格,则阻止序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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