简体   繁体   English

为什么List(Int32)的JSON序列化为ArrayList?

[英]Why does List(of Int32) get JSON serialized as ArrayList?

I am trying to serialize a List(Of Int32) using the JavaScriptSerializer . 我正在尝试使用JavaScriptSerializer序列化List(Of Int32) It seems to work until I try to Deserialize the object back to a List, at which point I get this error: 在尝试将对象Deserialize列表之前,它似乎一直有效,这时出现此错误:

Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.List`1[System.Int32]'. 无法将类型为“ System.Collections.ArrayList”的对象转换为类型为“ System.Collections.Generic.List`1 [System.Int32]”。

My code is below. 我的代码如下。 Can anyone please explain why, even when I explicitly cast to the correct type, that the list is automatically saved as an ArrayList? 谁能解释为什么即使我显式转换为正确的类型时,列表也自动保存为ArrayList?

Thanks in advance. 提前致谢。

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

The error line is this: 错误行是这样的:

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

JSON doesn't store the server-side representation; JSON不存储服务器端表示形式。 it wouldn't know that it's a List, so it has to go generic. 它不知道这是一个列表,因此必须通用。 But you should be able to do this to get it back: 但是您应该能够执行以下操作以将其取回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM