我在ASP.NET中使用VB,我一直在尝试将以下JSON反序列化大约4天,但没有成功。
问题是我在下面的代码返回空值。我想获得我声明的每个类成员的JSON结果,包括每个产品的价格和运费值。
任何人都可以指出我在
方面的正确方向1。)为什么我一直得到空值和
2。)如果我声明的类对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
Imports Newtonsoft.Json.Linq
Public Class inventories
Public Property price As Double
Public Property shipping As Double
End Class
Public Class product
Public Property googleid As String
Public Property title As String
Public Inventories As inventories()
End Class
Public Class Items
Public Property product As product()
Public Property kind As String
Public Property id As String
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 from Google
Dim google_json_string As String
google_json_string = json_text.Text
'2. Deserialize JSON - Method 1
Dim jss As New JavaScriptSerializer
Dim ds_results = jss.Deserialize(Of List(Of Items))(google_json_string)
result1.Text = ds_results.Count
result2.Text = ds_results(0).kind
End Sub
End Class
(更新)我已经更新了代码以包含这样结构的类(感谢Dan-o):
Public Class g_JSON
Public Property items As List(Of Items)
End Class
Public Class Items
Public Property product As 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 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 from Google
Dim google_json_string As String
google_json_string = json_text.Text
'2. Deserialize JSON - Method 1
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
End Sub
End Class
现在,代码将编译没有问题,但是当我启动click事件时,我收到以下错误:
没有为'product []'的类型定义无参数构造函数。
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.MissingMethodException:没有为'product []'的类型定义无参数构造函数。
来源错误: 第38行:Dim ds_results = jss.Deserialize(of g_JSON)(google_json_string)
这是什么意思,我如何为product()创建无参数构造函数?
谢谢你看看!
答案 0 :(得分:2)
根据jsonlint,您的json无效(“库存”数组后的逗号)。
答案 1 :(得分:1)
你忘记了容器......掌握一切的课程......
Class something
Public property kind as string = String.Empty
Public property items as list(of Item) = Nothing
End Class
然后你反序列化为something
,而不是列表(项目)