如何使用Newtonsoft Json.net在这个反序列化的对象中循环/迭代?

时间:2018-09-27 22:53:30

标签: json vb.net json.net

我有以下JSON对象:-

    Public Class oPartner
        Public Property PartnerID() As String
        Public Property PartnerTitle() As String
        Public Property PartnerStrapline() As String
        Public Property PartnerData() As String
    End Class

以及以下partners.json JSON文件:-

[
  {
    "PartnerID": "1",
    "PartnerTitle": "TITLE1",
    "PartnerStrapline": "STRAP1",
    "PartnerData": "SOME INFO IN HERE",
    "PartnerImage": ""
  },
  {
    "PartnerID": "2",
    "PartnerTitle": "TITLE2",
    "PartnerStrapline": "STRAP2",
    "PartnerData": "SOME MORE INFO IN HERE",
    "PartnerImage": ""
  },
  {
    "PartnerID": "3",
    "PartnerTitle": "TITLE3",
    "PartnerStrapline": "STRAP3",
    "PartnerData": "MORE INFO",
    "PartnerImage": ""
  }
] 

所以我可以使用以下方法读取JSON并反序列化:-

Dim data As oPartner = JsonConvert.DeserializeObject(Of oPartner)(File.ReadAllText("c:\partners.json"))

但是我不知道如何在vb(或C#)中遍历json?

1 个答案:

答案 0 :(得分:1)

您的JSON表示对象数组,但是您尝试将其反序列化为单个实例。您需要反序列化为oPartner的数组(或列表)。像这样尝试:

Dim data As List(Of oPartner) = JsonConvert.DeserializeObject(Of List(Of oPartner))(File.ReadAllText("c:\partners.json"))

然后您可以像这样遍历列表:

For Each partner As oPartner In data
    Console.WriteLine(partner.PartnerID)
    Console.WriteLine(partner.PartnerTitle)
    Console.WriteLine(partner.PartnerStrapline)
    Console.WriteLine(partner.PartnerData)
    Console.WriteLine()
Next

提琴:https://dotnetfiddle.net/N8Im6q