我是 JSON 反序列化的新手,需要帮助解决我遇到的问题。当 JSON 中的所有类都表示为数组时,我创建了可以工作的类。但是,如果您仔细查看我需要使用的 JSON,您会注意到“属性”成员实际上是成员的成员,而不是数组。这似乎是我的代码失败的地方,我认为我在类定义中为产品使用了错误的“类型”。
以下是 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"
}
]
}
}
]
}
这是我的代码:
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
当我尝试获取 product(0) 的计数时,它应该返回 1 时什么也不返回。如果我尝试返回 product(0).title,则会收到以下错误:
指数超出范围。必须是非负数且小于集合的大小。参数名称:索引
该消息暗示没有为产品返回任何内容。非常感谢任何提示或帮助!
PS 顺便说一句,当我将 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"
}
]
}
]
}
]