JSON.NET中的条件对象序列化

时间:2013-05-17 01:02:38

标签: vb.net json.net

我一直试图找出一种方法来忽略某些对象根据某些条件被序列化。我能找到的是如何使用ShouldSerialize *方法忽略对象的属性,而不是如何忽略整个对象。

这是一个解释我情况的例子。公司可以拥有多名员工,员工可以是当前的也可以是非当前的。

Public Class Company
    Public Property Name As String
    Public Property Employees As List(Of Employee)
End Class

Public Class Employee
    Public Property FirstName As List(Of Name)
    Public Property LastName As List(Of Name)
    Public Property Current As Boolean
End Class

我希望能够忽略/排除非现行员工被序列化为json。

我现在能想到的唯一方法是将当前和非当前员工分成两个属性,这样我就可以将<JsonIgnoreAttribute()>用于非当前员工。

如:

Public Class Company
    Public Property Name As String
    Public Property CurrentEmployees As List(Of Employee)
    <JsonIgnoreAttribute()>
    Public Property PastEmployees As List(Of Employee)
End Class

Public Class Employee
    Public Property FirstName As List(Of Name)
    Public Property LastName As List(Of Name)
    Public Property Current As Boolean
End Class

但是我试图避免这种情况,因为我在实际情况中有很多这样的东西所以我不想将所有列表分成两个需要大量代码修改的列表。如果可以在json序列化方面完成它会很好。

任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

Json.Net支持条件序列化。 请查看以下链接以了解实施

http://james.newtonking.com/projects/json/help/html/ConditionalProperties.htm

答案 1 :(得分:0)

Json.NET中似乎没有内置功能可以让我实现所需的功能。我最终在Company类中添加了一个函数,它在被序列化为json之前“清理”了不需要的数据。

使用前面的例子:

Public Class Company
    Public Property Name As String
    Public Property Employees As List(Of Employee)

    ' Before serializing, call this function
    Public Function GetObjectToSerialize() As Company

        ' Clone the object
        Dim cleanObj As Company = CType(Me.MemberwiseClone, Company)

        If Me.Employees.Count > 0 Then
            cleanObj.Employees = New List(Of Employee)
            For Each empl As Employee In Me.Employees
                ' only include the current employees
                If Not empl.Current Then
                    cleanObj.Employees.Add(empl)
                End If
            Next
        End If
    End Function
End Class

Public Class Employee
    Public Property FirstName As List(Of Name)
    Public Property LastName As List(Of Name)
    Public Property Current As Boolean
End Class

现在我要做的就是每当我要序列化一个Company对象时,我调用GetObjectToSerialize()函数并反而序列化返回的对象。

Dim objToSave As Company = companyObj.GetObjectToSerialize()
Dim json As String = JsonConvert.SerializeObject(objToSave, Formatting.Indented)