2012-07-04 46 views
33

我想序列化一些遗留的对象,“懒创建”各种列表。我无法改变传统行为。Newtonsoft Json.NET可以跳过序列化空列表吗?

我已煮沸它到这个简单的例子:

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, “数字”:[] }

我会喜欢得到: { “身份”:123 }

也就是说,我想跳过任何列表,collec tions,数组或空的东西。

回答

49

如果你没有找到解决方案,the answer是非常简单的,当你设法追踪它。

如果您被允许扩展原始类,然后添加一个ShouldSerializePropertyName函数。这应该返回一个布尔值,指示是否应为该类的当前实例序列化该属性。在您的例子,这可能是这样的(未测试,但你应该得到的图片):

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

这个方法对我的作品(尽管在VB.NET)。如果你不允许修改原来的课程,那么在链接页面上描述的方法是可行的。

+12

你可以简化为'return(_numbers.Count> 0);' –

+2

我喜欢它!好一个。 –

+3

我可以用通用的方法吗?我不知道所有的属性名称,但希望所有空数组为空。 – Rohit

1

只要是pendantic commonorgarden,我构造的试验是否是:

public bool ShouldSerializecommunicationmethods() 
{ 
    if (communicationmethods != null && communicationmethods.communicationmethod != null && communicationmethods.communicationmethod.Count > 0) 
     return true; 
    else 
     return false; 
} 

为空列表往往会空了。感谢您发布解决方案。 ATB。

+3

您拥有的另一个选择是使用“NullValueHandling”属性:[JsonProperty(“yourPropertyName”,NullValueHandling = NullValueHandling.Ignore)]。这应该有助于减少对空检查的需求,这将对您的检查进行一些改进。只是觉得我会提到它,因为你可能会发现它很方便。 –

+0

在ShouldSerialize方法中,您仍然需要检查空值,否则调用ShouldSerialize将在空值上抛出异常。即使在检查ShouldSerialize方法时序列化程序被编码为忽略异常,所有引发的异常都会增加可能影响性能的不必要开销。因此,您可能首先检查空值,从而获得更多的收益。 –