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

查看:257
本文介绍了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.

推荐答案

如果你没有找到一个解决这个,<一个href=\"http://james.newtonking.com/projects/json/help/index.html?topic=html/ConditionalProperties.htm\">the当你设法追查答案是非常简单的。

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天全站免登陆