I have a custom collection type like below:
Namespace Collections
Public Class KeyValuePairCollection(Of TKey, TValue)
Inherits List(Of KeyValuePair(Of TKey, TValue))
Public Sub New()
MyBase.New()
End Sub
F开发者_如何学Goriend 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
I want to deserialize instances of this type from JSON using custom 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
Deserialization code:
Dim serializer As New JavaScriptSerializer
serializer.RegisterConverters(New CustomConverter(){New CustomConverter(Of Integer, String)})
serializer.Deserialize(Of MyClass)(serializedObject)
MyClass has a field of KeyValuePairCollection type. When I debug this code and set breakpoint to Deserialize method... this method is never called. I just get following exception:
The value "System.Collections.Generic.Dictionary
2[System.String,System.Object]" is not of type "System.Collections.Generic.KeyValuePair
2[System.Int32,System.String]" and cannot be used in this generic collection. Parameter name: value
NOTE
Everything is fine when I use List(Of KeyValuePair(Of Integer, String)) instead of KeyValuePairCollection(Of Integer, String) in MyClass
You are using the keyvalue pair of Integer
and String
when you call RegisterConverters
and in CustomConverter
you are looking for String, Object
, so it can't be matched.
So, you may want to change your Deserialize method, but I think you will have problems doing this by extending JavaScriptConverter
and you may need to do it without extending, but, I do this with C# not VB.NET so I am not certain your best approach.
精彩评论