Newtonsoft Json.NET 可以跳过序列化空列表吗? [英] Can Newtonsoft Json.NET skip serializing empty lists?

查看:22
本文介绍了Newtonsoft Json.NET 可以跳过序列化空列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化一些懒惰创建"各种列表的遗留对象.我无法更改旧行为.

I am trying to serialize some legacy objects that "lazy creates" various lists. I can not change the legacy behavior.

我把它归结为这个简单的例子:

I have boiled it down to this simple example:

public class Junk
{
    protected int _id;

    [JsonProperty( PropertyName = "Identity" )]
    public int ID 
    { 
        get
        {
            return _id;
        }

        set
        {
            _id = value;
        }
    }

    protected List<int> _numbers;
    public List<int> Numbers
    {
        get
        {
            if( null == _numbers )
            {
                _numbers = new List<int>( );
            }

            return _numbers;
        }

        set
        {
            _numbers = value;
        }
    }
}

class Program
{
    static void Main( string[] args )
    {
        Junk j = new Junk( ) { ID = 123 };

        string newtonSoftJson = JsonConvert.SerializeObject( j, Newtonsoft.Json.Formatting.Indented );

        Console.WriteLine( newtonSoftJson );

    }
}

目前的结果是:{身份":123,数字":[]}

The current results are: { "Identity": 123, "Numbers": [] }

我想得到:{身份":123}

I would like to get: { "Identity": 123 }

也就是说,我想跳过任何列表、集合、数组或诸如此类的空内容.

That is, I would like to skip any lists, collections, arrays, or such things that are empty.

推荐答案

如果您没有找到解决方案,答案当您设法追踪它时非常简单.

In case you didn't find a solution to this, the answer is remarkably simple when you manage to track it down.

如果允许您扩展原始类,则向其添加 ShouldSerializePropertyName 函数.这应该返回一个布尔值,指示是否应该为类的当前实例序列化该属性.在您的示例中,这可能看起来像这样(未经测试,但您应该得到图片):

If you are permitted to extend the original class then add a ShouldSerializePropertyName function to it. This should return a Boolean indicating whether or not that property should be serialized for the current instance of the class. In your example this might look like this (not tested but you should get the picture):

public bool ShouldSerializeNumbers()
{
    return _numbers.Count > 0;
}

这种方法对我有用(尽管在 VB.NET 中).如果您不允许修改原始类,那么链接页面上描述的 IContractResolver 方法就是要走的路.

This approach works for me (albeit in VB.NET). If you're not allowed to modify the original class then the IContractResolver approach described on the the linked page is the way to go.

这篇关于Newtonsoft Json.NET 可以跳过序列化空列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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