I'm new to JSON deserialization and need help with an issue I'm running into. I created classes that work when all the classes in the JSON are represented as arrays. However, if you take a close look at the JSON I am required to use you will notice the 'property' member is actual a member of a member and not an array. This seems to be where my code fails and I think that I am using the wrong 'type' for product in my class definition.
Here is an example of the JSON:
{
"kind": "shopping#products",
"items":
[{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/8040/8382012077897342942",
"product": {
"googleId": "8382012077897342942",
"title": "LEGO Star Wars™: Jabba's Palace™ (9516)",
"description": "Rescue Han Solo from Jabba the Hutt's desert palace!",
"inventories": [
{
"price": 119.99,
"shipping": 12.95,
"currency": "USD"
}
]
}
}
]
}
Here is my Code:
Imports System.Web.Script.Serialization
Public Class g_JSON
Public Property items As List(Of Items)
End Class
Public Class Items
Public Property product As List(Of product)
Public Property kind As String
Public Property id As String
End Class
Public Class product
Public Property googleid As String
Public Property title As String
Public Inventories As List(Of inventories)
End Class
Public Class inventories
Public Property price As Double
Public Property shipping As Double
End Class
Partial Class JSON_Test
Inherits System.Web.UI.Page
Protected Sub getbutton_Click(sender As Object, e As System.EventArgs) Handles getbutton.Click
' 1. Get JSON string
Dim google_json_string As String
google_json_string = json_text.Text
'2. Deserialize JSON
Dim jss As New JavaScriptSerializer
Dim ds_results = jss.Deserialize(Of g_JSON)(google_json_string)
result1.Text = ds_results.items(0).id
result2.Text = ds_results.items(0).kind
result3.Text = ds_results.items(0).product(0).title 'errors here
End Sub
End Class
When I try to get a count of product(0) it returns nothing when it should return 1. If I try to return product(0).title I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
The message implies nothing is being returned for product. Any hints or help is greatly appreciated!
P.S. By the way, when I change the JSON to include product as a parameter[], like below, it works.
{
"kind": "shopping#products",
"items":
[{
"kind": "shopping#product",
"id": "tag:google.com,2010:shopping/products/8040/8382012077897342942",
"product": [{
"googleId": "8382012077897342942",
"title": "LEGO Star Wars™: Jabba's Palace™ (9516)",
"description": "Rescue Han Solo from Jabba the Hutt's desert palace!",
"inventories": [
{
"price": 119.99,
"shipping": 12.95,
"currency": "USD"
}
]
}
]
}
]