2013-05-17 90 views
4

我一直在試圖找出一種方法來忽略某些對象被基於某些條件序列化。我所能找到的就是如何使用ShouldSerialize *方法忽略對象的屬性,而不是如何忽略整個對象。JSON.NET中的條件對象序列化

下面是一個解釋我的情況的例子。一個公司可以有多個員工,員工可以是現任的也可以是非現任的。

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序列化方面完成,那將會很好。

任何幫助表示讚賞。謝謝!

回答

0

有似乎沒有在Json.NET的功能,可以讓我實現需要什麼建。我最終在公司類中添加了一個函數,在序列化成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 

所有我現在要做的是,每當我即將序列化對象的公司,我叫GetObjectToSerialize()函數和序列化返回的對象來代替。

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

這不是「有條件的序列化」,這是有選擇地克隆一個對象的成員,然後序列化整個克隆。您可以使用LINQ輕鬆完成此操作。我會說原來的問題是誤導性的 –