2017-06-22 24 views
1

我有一個巨大的類,有很多信息。我想打印給JSON的一些信息,但不是所有信息。當我將對象序列化爲JSON時,它會打印所有信息。.NET將對象合併到其他對象

所以我想我爲我想用JSON打印的數據創建了一個模板類。然後我想從原始類中複製模板中存在的所有值,並跳過其餘部分。然後我可以序列化該模板類。

例如: enter image description here

現在我試圖做到的是將數據複製從placeplaceJSON

enter image description here

那麼結果會是這樣的:enter image description here

我想我應該循環遍歷placeJSON所有屬性,如果同一屬性名在place存在,那麼我應該複製該值。但是它也需要爲Country這樣的嵌套類完成。

這可能怎麼辦?

+3

許多JSON庫支持的屬性用於標記某些性質不該」序列化。檢查您正在使用的序列化程序的文檔。 – mason

+0

@mason嚴重...所以我一直在錯誤的道路上?我使用Newtonsoft JSON。我將檢查文檔 – NLAnaconda

+1

'JsonIgnoreAttribute' – Plutonix

回答

0

我開始寫一個解決方案,並在這裏分享。它可能不完美,但它是一個開始。

Public Shared Function mergeObjectInTemplatedata(template As Object, 
               source As Object, 
               Optional parents As List(Of String) = Nothing) As Object 

    If parents Is Nothing Then 
     parents = New List(Of String) 
    End If 

    For Each prop As PropertyInfo In template.GetType().GetProperties() 

     Dim value As Type = prop.GetValue(template).GetType() 
     If value = GetType(String) Or value = GetType(Integer) Then 

      prop.SetValue(template, getFromSource(source, parents, prop.Name)) 

     Else 
      parents.Add(prop.Name) 
      mergeObjectInTemplatedata(prop.GetValue(template), source, parents) 
     End If 

    Next 

    Return template 
End Function 

Private Shared Function getFromSource(source As Object, 
             location As List(Of String), 
             propertyName As String) As Object 

    Dim obj As Object = source 
    For Each item As String In location 
     obj = CallByName(obj, item, CallType.Get) 
    Next 
    Return CallByName(obj, propertyName, CallType.Get) 
End Function 
0

是不是有一個原因,你不只是創建一個新的匿名類型序列化成JSON?

例如(我只知道C#,不是VB,問題被標記爲C#,所以我希望這是可用的!):

class Place { 
     public string Name { get; set; } 
     public CountryItem Country { get; set; } 
     //other properties... 
     public object ToPlaceJson() { 
      return new { name = Name, country = Country }; 
     } 
} 
+0

謝謝。我想這樣做的原因是因爲我必須做很多次(真的很多次)。我認爲只是把它合併到另一個,而不是寫'name = Name','country = Country','latitude = Latitude','longitude = Longitude',..,...,... [ * 100次]。我想如果名稱是相同的,應該可以通過編程來完成。 – NLAnaconda