反序列化JSON数组集合问题VB.NET

up9lanfz  于 2023-03-04  发布在  .NET
关注(0)|答案(2)|浏览(116)

获取以下错误
发生序列化异常:
'无法将当前JSON对象(例如{" name ":" value "})反序列化为类型"System. Collections. Generic. List" 1 []",因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。若要修复此错误,请将JSON更改为JSON数组(例如[1,2,3]),或者更改反序列化的类型,使其成为可以从JSON对象反序列化的普通. NET类型(例如,不是像整数这样的基元类型,也不是像数组或列表这样的集合类型)。还可以将JsonObjectAttribute添加到该类型中,以强制其从JSON对象反序列化。
我已经让它在一个有多个selectToken的循环中工作了,但是调用50多个selectToken有点慢,我想加快它的速度。
我将省略一些值名称,因为它相当长。
但是假设我有嵌套类

    • 编辑**:这是使用Newtonsoft JSON库的
Public Class Orders
    Public recordSetTotal As Integer

    Public Class ordersList 'orders list is an array in the JSON data source
        Public Class orderDetails
            Public grandTotal As Single
            Public placedDate As String
        End Class
    
        Public Class address
            Public postcode As String
            Public addressLine() As String 'this is an array in the JSON data source
        End Class
    End Class
End Class
'orderData is the JSON string block
Dim ordersList As List(Of Orders) = JsonConvert.DeserializeObject(Of List(Of Orders))(orderData)

orderData可能看起来像这样(我已经剪下了json作为示例,所以可能在json中有错误,但不应该在源代码中)。我只为ordersList放置了1个数组条目,但它将有多个并匹配recordSetTotal

{
   "recordSetTotal":10,
   "ordersList":[
      {
         "orderDetails":{
            "grandTotal":50.0000,
            "placedDate":"2022-12-25 12:00:00.000"
         },
         "addressLine":[
            "123 Fake St",
            "Somewhere",
            "ABG"
         ]
      }
   ]
}

打破一些嵌套以便使ordersList成为数组是否更好?

Public Class Orders
    Public recordSetTotal As Integer
    Public ordersList() as ordersList
End Class

Public Class ordersList 'orders list is an array in the JSON data source
    Public Class orderDetails
        Public grandTotal As Single
        Public placedDate As String
    End Class
    
    Public Class address
        Public postcode As String
        Public addressLine() As String 'this is an array in the JSON data source
    End Class
End Class

如果我要去嵌套类,数组应该是这样的:

Public ordersList() as ordersList

或者这个:

Public ordersList as ordersList()
sc4hvdpw

sc4hvdpw1#

您需要添加一个根类,您的类应该是

Public Class Root
        Public Property recordSetTotal As Integer
        Public Property ordersList As OrdersList()
    End Class

  Public Class OrdersList
        Public Property orderDetails As OrderDetails
        Public Property addressLine As String()
    End Class

Public Class OrderDetails
        Public Property grandTotal As Double
        Public Property placedDate As String
    End Class

和代码

Dim ordersList As List(Of Orders) = JsonConvert
                                   .DeserializeObject(Of Root)(orderData).ordersList
tp5buhyn

tp5buhyn2#

所以,如果有人想知道,请查看GSerg在我的帖子上留下的评论。
所有的类都必须是非嵌套的,并且类内部的所有东西都必须是公共属性,包括类外部的对象。
例如,数组必须是公共属性ordersList as List(of ordersList),而不是公共属性ordersList()as ordersList
阅读json就像Dim反序列化一样简单,因为订单= JsonConvert.DeserializeObject(Of Orders)(json)
任何没有匹配名称作为公共属性的json键/字段显然不会被读入结果。

相关问题