I am attempting to deserialize a simple JSON array to .NET objects using the JSON.NET library in visual basic.
For the life of me, I cannot figure out what I am doing wrong here. My JSON string deserializes into appropriate objects (9 in total), but none of the properties are populated.
My code:
Public Class result
Public Property id As Integer
Public Property vote_percentage As String
Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal vote_percentage As String)
Me.id = id
Me.vote_percentage = vote_percentage
End Sub
End Class
The JSON data I am trying to deserialize looks like this:
[{"finalist":{"id":12,"vote_percentage":"28"}},{"finalist":{"id":13,"vote_percentage":"6"}},{"finalist":{"id":14,"vote_percentage":"4"}},{"finalist":{"id":15,"vote_percentage":"3"}},{"finalist":{"id":16,"vote_percentage":"7"}},{"finalist":{"id":17,"vote_percentage":"1"}},{"finalist":{"id":18,"vote_percentage":"47"}},{"finalist":{"id":19,"vote_percentage":"2"}},{"finalist":{"id":20,"vote_percentage":"1"}}]
Finally my deserialization:
Dim Results As New List(Of result)
Results = JsonConvert.DeserializeObject(Of List(Of result))(_result)
The result is 9 objects that don't have any property values assigned.
I am racking my brain, so if someone could throw me a bone I would appreciate it.
Thanks.
UPDATE:
So here is the change I made that got this to work:
- Modified my result class to contain a property finalist of type finalist
Created a new class finalist with properties id and vote_percentage
Public Class finalist Public Property id As Integer Public Property vote_percentage As String Public Sub New() End Sub Public Sub New(ByVal id As Integer, ByVal vote_percentage As String) Me.id = id Me.vote_percentage = vote_percentage End Sub End Class Public Class result Public Property finalist As finalist Public Sub New() finalist = New finalist End Sub Public Sub New(ByVal id As Integer, ByVal vote_percentage As String) Me.finalist = New finalist(id, vote_percentage) End Sub End Class
Left the deserialization alone:
_result = System.Text.Encoding.ASCII.GetString(data)
Dim Results As New List(Of result)
Results = JsonConvert.DeserializeObject(Of List(Of result))(_result)
RaiseEvent VoteCompleted(loopCounter, _VoteCount, time, _result)
And it works.
A note for new people (like myself). When using JSON.NET you have to have constructor methods (i.e. Sub New) in order for the properties to get set during the Deserialization call.