Newtonsoft JsonConvert,覆盖当前的IEnumerable项目

问题描述:

我有一个对象,它看起来是这样的:Newtonsoft JsonConvert,覆盖当前的IEnumerable项目

Public Class ExportOptions 

     Public Sub New() 
      CategoryIDs = {New Guid("30ndd837-7a2c-477c-b892-67f129f7af4e")} 
     End Sub 

     Property CategoryIDs As IEnumerable(Of Guid) 

    End Class 

然后我反序列化JSON像这样:

Newtonsoft.Json.JsonConvert.DeserializeObject(Of ExportOptions)(JSONString) 

问题是在价值观JSON没有进入CategoryIDs属性?相反,我只剩下构造函数中使用的单个值。

如果我改变CategoryIDs到一个List(GUID的),那么新categoryIDs被添加到列表中,当我需要他们来覆盖当前的项目。

在构造函数中添加的值是一个默认值,并且在客户端没有传递任何东西的情况下必须存在。

管理到底工作了这一点我自己: -

  Newtonsoft.Json.JsonConvert.DeserializeObject(Of AmazonSimpleExportOptions)(JSONString, 
                         New Newtonsoft.Json.JsonSerializerSettings With { 
                          .ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace}) 

Public Class ExportOptions 

     Private defaultGuid As New Guid("30ndd837-7a2c-477c-b892-67f129f7af4e") 
     Private cats as List(Of Guid) = {defaultGuid} 

     Public Sub New() 

     End Sub 

     Property CategoryIDs As List(Of Guid) 
      Get 
       Return cats 
      End Get 

      Set(ByVal Value As List(Of Guid)) 
       cats = Value 
       If cats.Count = 0 Then cats.Add(defaultGuid) 
      End Set 
     End Property 
End Class 
+0

感谢罗伊,这是我目前回落的解决方案。因为实际的解决方案使用接口,并且在整个解决方案中会有许多这样的类以及不同的列表,所以尽可能自动化会很好! – pingoo 2012-02-03 15:11:57

+0

@ Rene147如果你不想碰序列化类可行的替代方案:不是默认加入的项目列表,访问它使用CategoryIDs.DefaultIfEmpty(新的GUID(“30ndd837-7a2c-477C-b892-67f129f7af4e时“)) – 2012-02-03 15:15:31