【问题标题】:Load Json file in VB.NET/C# using newtonsoft使用 newtonsoft 在 VB.NET/C# 中加载 Json 文件
【发布时间】:2020-12-01 17:38:07
【问题描述】:

我有这种 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)

但是我做错了,我无法遍历每个订单中的文章列表。 是的,我已经检查了与此问题相关的所有 Q/A,问题是空引用,不确定是 JSON 格式问题、Newtonsoft 问题还是我的错。

【问题讨论】:

    标签: json vb.net json.net


    【解决方案1】:

    您的数据模型与您的 JSON 不同。具体来说,顶级 JSON 对象具有属性"orderId""customerID""OrderArticle",而Response 具有showOrders 具有productIDorderDatearticles。只有低级对象OrderArticle 看起来正确。

    您需要修复您的数据模型,以便 VB.NET 和 JSON 属性对应——即具有匹配的名称和层次结构。在 How to auto-generate a C# class file from a JSON string 中列出的工具中,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                                
    

    演示小提琴here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      相关资源
      最近更新 更多