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序列化端完成就好了。

感谢任何帮助。谢谢!

Json。Net支持条件序列化。查看下面的实现链接

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

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)

相关内容

  • 没有找到相关文章