Json在Vb中反序列化嵌套对象(Newtonsoft)

时间:2019-12-20 10:51:09

标签: json vb.net json.net

基本上,我正在尝试从API中获取数据。

我的JSON是:

[
  {
    "id": 101,
    "items": [
      {
        "id": 91,
        "quantity": 141,
        "size": "12",
        "assigned": false,
        "item": {
          "pk": 27,
          "title": "test title",
          "description": "test description",
          "designer": "designer",
          "category": 4,
          "size": "12,14,16",
          "image": "media/products/indir.jpg",
          "price": 31.0,
          "resin_gr": 31.0
        }
      },
      {
        "id": 92,
        "quantity": 18,
        "size": "14",
        "assigned": false,
        "item": {
          "pk": 26,
          "title": "Bileklik 5",
          "description": "bileklik",
          "designer": "designer",
          "category": 2,
          "size": "12,14,16",
          "image": "media/products/NB00316.png",
          "price": 50.0,
          "resin_gr": 14.0
        }
      }
    ]
  }
]

我的课程是:

 Public Class Orders
        Public Property id As Integer
        Public Property items As IEnumerable(Of OrderItems)
    End Class

    Public Class OrderItems
        Public Property id As Integer
        Public Property quantity As String
        Public Property size As String
        Public Property assigned As String
        Public Property item As List(Of OrderProduct)
    End Class

    Public Class OrderProduct
        Public Property pk As Integer
        Public Property title As String
        Public Property description As String
        Public Property designer As String
        Public Property category As String
        Public Property size As String
        Public Property image As String
        Public Property price As String
        Public Property resin_gr As String
    End Class

我正在尝试像这样解析JSON:

Dim result As IEnumerable(Of Orders) = JsonConvert.DeserializeObject(Of IEnumerable(Of Orders))(JSONDATA)

我在路径'[0] .items [0] .item.pk'(第1行,位置86)上遇到错误。

我尝试了什么:

我将orders.item更改为列出但没有任何更改。

我该怎么办?

1 个答案:

答案 0 :(得分:-2)

Public Class Orders
    Public ID As Integer
    Public Items As IEnumerable(Of OrderItems)
End Class
Public Class OrderItems
    Public ID As Integer
    Public quantity As Integer
    Public size As Integer
    Public assigned As Boolean
    Public Item As OrderProduct
End Class
Public Class OrderProduct
    Public pk As Integer
    Public title As String
    Public description As String
    Public designer As String
    Public category As Integer
    Public size As String
    Public image As String
    Public price As Double
    Public resin_gr As Double
End Class

编辑:就像朋友评论中一样,之所以有用,是因为您试图在此处将对象解析为列表:

Public Property item As List(Of OrderProduct)

何时需要

Public Item As OrderProduct

我为指定的JSON重新创建自定义对象时,以某种方式错过了该问题并解决了该问题。