I have some JSON data that looks like this:
{
"data":
[{
"name":"John Smith",
"id":"12345"
}]
}
I have a pair of serializeable classes like so:
<Serializable()> _
Public Class User
Private _name As String
Private _id As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property id() As String
Get
Return _id
End Get
S开发者_高级运维et(ByVal value As String)
_id = value
End Set
End Property
End Class
<Serializable()>
Public Class UserData
Private _data As List(Of User)
Public Property data() As List(Of User)
Get
Return (_data)
End Get
Set(ByVal value As List(Of User))
_data = value
End Set
End Property
End Class
When I try to deserialize as an object:
Dim serializer As New JavaScriptSerializer()
Dim userResult As Object = serializer.DeserializeObject(json)
I get one root object with key "data", and value another object with 2 children, with keys "name" and "id", and the appropriate values one might expect. But when I try to cast that object to my UserData
type, it returns Nothing
. I had this code working at some point, but now that I am returning to it and attempting to use it again, it seems some code rot has set in and it has stopped working.
Here is how I am attempting to get the deserialized data as a UserData
object:
Dim userResult As UserData = TryCast(serializer.DeserializeObject(json), UserData)
I was able to fix this issue by changing
Dim userResult As UserData = TryCast(serializer.DeserializeObject(json), UserData)
to
Dim userResult As UserData = serializer.Deserialize(Of UserData)(json)
Not exactly sure what the functional difference here is, but that got me the result i wanted.
精彩评论