【问题标题】:Why does List(of Int32) get JSON serialized as ArrayList?为什么 List(of Int32) 将 JSON 序列化为 ArrayList?
【发布时间】:2013-08-28 15:22:31
【问题描述】:

我正在尝试使用JavaScriptSerializer 序列化List(Of Int32)。在我尝试将 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))

【问题讨论】:

    标签: asp.net json vb.net serialization asp.net-4.5


    【解决方案1】:

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

    Ctype(d.Item("myList"), ArrayList).Cast(Of Integer)().ToList()
    

    【讨论】:

    • 太棒了。我使用 .NET 近十年了,从来不知道.Cast(Of Integer)。像魅力一样工作 - 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2015-09-12
    • 2021-06-14
    • 2015-06-07
    • 2021-01-14
    相关资源
    最近更新 更多