0

我正在尝试List(Of Int32)使用JavaScriptSerializer. 在我尝试Deserialize将对象返回到列表之前,它似乎有效,此时我收到此错误:

无法将“System.Collections.ArrayList”类型的对象转换为“System.Collections.Generic.List`1[System.Int32]”类型。

我的代码如下。谁能解释为什么即使我明确地转换为正确的类型,列表也会自动保存为 ArrayList?

提前致谢。

Private Property _serialized As String
    Get
        Return ViewState("_serialized")
    End Get
    Set(value As String)
        ViewState("_serialized") = value
    End Set
End Property

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim l As New List(Of Int32) From {2, 4, 6, 8, 10}
        Dim d As New Dictionary(Of String, Object)
        d.Add("myList", l)
        Dim js As New Script.Serialization.JavaScriptSerializer
        Me._serialized = js.Serialize(d)
    End If
End Sub

Protected Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
    Dim js As New Script.Serialization.JavaScriptSerializer
    Dim d As Dictionary(Of String, Object) = js.Deserialize(Of Dictionary(Of String, Object))(Me._serialized)
    Dim l As List(Of Int32) = CType(d.Item("myList"), List(Of Int32))
    For Each i As Int32 In l
        Trace.Warn(i.ToString)
    Next
End Sub

错误行是这样的:

Dim l As List(Of Int32) = CType(d.Item("myList"), List(Of Int32))
4

1 回答 1

1

JSON 不存储服务器端表示;它不会知道它是一个列表,所以它必须是通用的。但是您应该能够这样做以将其取回:

Ctype(d.Item("myList"), ArrayList).Cast(Of Integer)().ToList()
于 2013-08-28T15:26:48.720 回答