JSON doesn't store the server-side representation; 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()
Pergunta
I am trying to serialize a List(Of Int32)
using the JavaScriptSerializer
. It seems to work until I try to Deserialize
the object back to a List, at which point I get this error:
Unable to cast object of type 'System.Collections.ArrayList' to type '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?
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))
Solução
JSON doesn't store the server-side representation; 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()