我试图使用VB.NET 2.0反序列化JSON字符串

时间:2015-04-12 19:33:45

标签: json vb.net deserialization

我正在尝试反序列化JSON字符串并且卡住了。

我的字符串是

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

我已将其保存在字符串embels

我的班级是

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

BUt我收到错误'调用目标抛出了异常'

1 个答案:

答案 0 :(得分:0)

问题在于:

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

您告诉Deserializer它正在对Embellishments对象执行操作,但尝试在集合对象中捕获结果。错误消息告诉您,如果您说该字符串是单个对象,则它无法反序列化为它们的List。换句话说,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

支持字段类型与属性Getter / Setter类型不匹配,将导致混乱。更改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