2011-03-21 45 views
0

我有類似下面的自定義集合類型:JavascriptDeserializer定製收集

Namespace Collections 
    Public Class KeyValuePairCollection(Of TKey, TValue) 
     Inherits List(Of KeyValuePair(Of TKey, TValue)) 

     Public Sub New() 
      MyBase.New() 
     End Sub 

     Friend Sub New(ByVal innerCollection As IEnumerable(Of KeyValuePair(Of TKey, TValue))) 
      Me.New() 
      Me.AddRange(innerCollection) 
     End Sub 

     Public Overloads Sub Add(ByVal key As TKey, ByVal value As TValue) 
      Dim item As New KeyValuePair(Of TKey, TValue)(key, value) 
      MyBase.Add(item) 
     End Sub 

    End Class 
End Namespace 

我想使用自定義JavascriptConverter

Public Class CustomConverter(Of TKey, TValue) 
     Inherits JavaScriptConverter 

     Public Overrides ReadOnly Property SupportedTypes() As IEnumerable(Of Type) 
      Get 
       Return New ReadOnlyCollection(Of Type)(New List(Of Type) _ 
       (New Type() {GetType(KeyValuePairCollection(Of TKey, TValue))})) 
      End Get 
     End Property 

     Public Overrides Function Serialize(ByVal obj As Object, _ 
     ByVal serializer As JavaScriptSerializer) As IDictionary(Of String, Object) 
      Throw New NotSupportedException("This class can be used only for deserialization.") 
     End Function 

     Public Overrides Function Deserialize(ByVal dictionary As IDictionary(Of String, Object), _ 
     ByVal type As Type, ByVal serializer As JavaScriptSerializer) As Object 

      Return Nothing 

     End Function 
    End Class 

反序列化代碼從JSON反序列化這種類型的實例:

Dim serializer As New JavaScriptSerializer 
serializer.RegisterConverters(New CustomConverter(){New CustomConverter(Of Integer, String)}) 
serializer.Deserialize(Of MyClass)(serializedObject) 

MyClass的具有KeyValuePairCollection類型的字段。 當我調試此代碼並將斷點設置爲Deserialize方法時...此方法從不調用。我只是得到以下情況例外:

值 「System.Collections.Generic.Dictionary 2[System.String,System.Object]" is not of type "System.Collections.Generic.KeyValuePair 2 System.Int32,System.String]」 ,不能在這個通用 收集使用。參數名:價值

注意

一切都很好,當我使用List(中KeyValuePair(整數,字符串)),而不是KeyValuePairCollection(整數,字符串)MyClass中

回答

0

你正在使用的鍵值對IntegerString,當你調用RegisterConvertersCustomConverter你正在尋找String, Object,所以它不能匹配。所以,你可能想要改變你的Deserialize方法,但我認爲你通過擴展JavaScriptConverter來解決這個問題,你可能需要不擴展,但是,我用C#而不是VB.NET來做這件事,所以我我不確定你的最佳做法。

+0

感謝您的回答。但我不確定我是否理解......你能澄清它嗎?爲什麼我會在使用JavascriptConverter時遇到問題?如何在沒有JavascriptConverter類的情況下對我的集合進行反序列化?你能提供一個關於C#的例子嗎? – Egor4eg 2011-03-22 08:06:57