用于自定义集合的Javascriptserializer

时间:2011-03-21 17:06:59

标签: .net json deserialization

我有一个自定义集合类型,如下所示:

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

从JSON反序列化此类型的实例
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

反序列化代码:

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]”   并且不能用于此通用   采集。参数名称:值

注意

当我在MyClass中使用List(Of KeyValuePair(Of Integer,String))而不是KeyValuePairCollection(Of Integer,String)时,一切都很好

1 个答案:

答案 0 :(得分:0)

当您拨打Integer时,您正在使用StringRegisterConverters的键值对,而CustomConverter正在寻找String, Object,因此它可以'匹配。

所以,您可能想要更改Deserialize方法,但我认为通过扩展JavaScriptConverter来执行此操作会遇到问题,您可能需要在不扩展的情况下执行此操作,但是,我使用C#而不是VB执行此操作。 NET所以我不确定你最好的方法。