我有这样的JSON文件:
[{
"orderId": "36186",
"customerID": "584",
"OrderArticle": [
{
"productId": "1780",
"webCategory": "Cat1",
"articleQty": "1",
"perQty": ""
},
{
"productId": "2587",
"webCategory": "Cat3",
"articleQty": "58",
"perQty": ""
}
]
//..........
}]
以及这些类别:
Public Class Response
Public Property show() As Orders
End Class
Public Class Orders
Public Property productID As String
Public Property orderDate As String
Public Property articles() As New List(Of Orderarticle)
End Class
Public Class Orderarticle
Public Property productId As String
Public Property webCategory As String
Public Property articleQty As String
Public Property perQty As String
End Class
OrderArticle可能包含1到x个文章。
我正在尝试:
Dim json As String = My.Computer.FileSystem.ReadAllText(filePath)
Dim orderList = JsonConvert.DeserializeObject(Of List(Of Response))(json)
但我做错了,我无法按每个顺序迭代文章列表。是的,我已经检查了与此问题相关的所有问答,问题是空引用,不确定是JSON格式问题、Newtonsoft问题还是我的错。
您的数据模型与JSON不相似。具体而言,顶级JSON对象具有属性"orderId"
、"customerID"
和"OrderArticle"
,而Response
具有show
,Orders
具有productID
、orderDate
和articles
。只有低级别对象OrderArticle
看起来是正确的。
您需要修复数据模型,使VB.NET和JSON属性相对应,即具有匹配的名称和层次结构。在如何从JSON字符串自动生成C#类文件中列出的工具中,https://jsonutils.com/支持VB.NET和c#,所以我自动生成了以下更正的模型:
Public Class Response
Public Property orderId As String
Public Property customerID As String
Public Property OrderArticle As New List(Of OrderArticle) ' Modified from Public Property OrderArticle As OrderArticle()
End Class
Public Class OrderArticle
Public Property productId As String
Public Property webCategory As String
Public Property articleQty As String
Public Property perQty As String
End Class
我对自动生成的模型所做的唯一更改是将OrderArticle
从数组更改为列表。然后,要对文章进行迭代,请执行以下操作:
Dim orderList = JsonConvert.DeserializeObject(Of List(Of Response))(json)
Dim i = 0
For Each response in orderList
For Each article in response.OrderArticle
Console.WriteLine("Article {0}: ", System.Threading.Interlocked.Increment(i))
Console.WriteLine(" productId={0}, webCategory={1}, articleQty={2}, perQty={3}",
article.productId, article.webCategory, article.articleQty, article.perQty)
Next
Next
在这里演示小提琴。