Can Newtonsoft Json.NET skip serializing empty lists?

前端 未结 4 1941
花落未央
花落未央 2020-11-28 11:59

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:

4条回答
  •  醉梦人生
    2020-11-28 12:04

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

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

    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.

提交回复
热议问题