簡體   English   中英

我正在嘗試使用VB.NET 2.0反序列化JSON字符串

[英]I am trying to deserialize a JSON string using VB.NET 2.0

我正在嘗試反序列化JSON字符串並卡住。

我的繩子是

[{"BasketItemID":3,"ProductEmbellishmentID":8,"EmbellishmentText":"lfo","Price":9.95},{"BasketItemID":3,"ProductEmbellishmentID":3,"EmbellishmentText":"rc","Price":9.95}]

我已將其保存在琴弦中

我的課是

Public Class Embellishments
Private _BasketItemID As Integer
Private _ProductEmbellishmentID As Integer
Private _EmbellishmentText As Integer
Private _Price As Integer


Public Property BasketItemID() As Integer
    Get
        Return _BasketItemID
    End Get

    Set(value As Integer)
        _BasketItemID = value
    End Set
End Property
Public Property ProductEmbellishmentID() As String
    Get
        Return _ProductEmbellishmentID
    End Get
    Set(value As String)
        _ProductEmbellishmentID = value
    End Set
End Property
Public Property EmbellishmentText() As String
    Get
        Return _EmbellishmentText
    End Get
    Set(value As String)
        _EmbellishmentText = value
    End Set
End Property
Public Property Price() As Decimal
    Get
        Return _Price
    End Get
    Set(value As Decimal)
        _Price = value
    End Set
End Property

最終班

我嘗試反序列化使用

        Dim jss As New JavaScriptSerializer()
        Dim emblist As List(Of Embellishments) = jss.Deserialize(Of Embellishments)(embels)

但是出現錯誤“類型”值的值不能轉換為“ System.Collections.Generic.List(Of Embellishments)”

我現在被困住了。 誰能給我任何指示? 謝謝

編輯

感謝@Plutonix我現在嘗試了

    Dim errormessage As String=''
Dim Count As Integer = 0
Try
    Dim jss As New JavaScriptSerializer()
    Dim emblist As List(Of Embellishments) = jss.Deserialize(Of List(Of Embellishments))(embels)

    For Each em As Embellishments In emblist
        Count = Count + 1
    Next

Catch ex As Exception

    errormessage = ex.Message

End Try

我收到錯誤“調用的目標已拋出異常”

問題是這樣的:

Dim emblist As List(Of Embellishments) = jss.Deserialize(Of Embellishments)(embels)

您要告訴Deserializer它正在對Embellishments對象起作用,但試圖將結果捕獲到集合對象中。 錯誤消息告訴您,如果您說字符串是單個對象,則無法將其反序列化為它們的列表。 換句話說, EmbellishmentsList(of Embellishments)是不同的東西。

由於在字符串中的多個對象,正確的語法是(我叫我的Basket ):

Dim emblist = jss.Deserialize(Of List(Of Basket))(embels)

在VS2010及更高版本中,可以使用Option Infer分配類型。 這也是有效的,並將創建一個購物籃項目數組:

Dim emblist = jss.Deserialize(Of Basket())(embels)

更重要的是,您應該啟用Option Strict。 這導致廢話:

Private _ProductEmbellishmentID As Integer
Public Property ProductEmbellishmentID() As String

支持字段Type與屬性Getter / Setter type不匹配,將導致混亂。 更改Property語句以匹配專用后備字段的類型。 同樣,在VS2010之后,您可以使用自動實現屬性來減少所有樣板代碼:

Public Class Basket
    Public Property BasketItemID As Integer
    Public Property ProductEmbellishmentID As Integer
    Public Property EmbellishmentText As String
    Public Property Price As Decimal

End Class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM