[英]LINQ to Entities does not recognize the method 'Int32 get_Item(Int32)' method exception
[英]Why does List(of Int32) get JSON serialized as ArrayList?
我正在嘗試使用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))
JSON不存儲服務器端表示形式。 它不知道這是一個列表,因此必須通用。 但是您應該能夠執行以下操作以將其取回:
Ctype(d.Item("myList"), ArrayList).Cast(Of Integer)().ToList()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.