4

我一直在试图找出一种方法来忽略某些对象基于某些条件被序列化。我所能找到的只是如何使用 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 序列化端完成,那就太好了。

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

4

2 回答 2

1

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

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

于 2013-05-20T06:33:59.250 回答
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)
于 2013-12-18T23:17:40.300 回答