在json字符串中反序列化多个对象

时间:2016-07-11 03:50:03

标签: json vb.net

我正在使用一个在json字符串中发送多个对象的Web服务。

{  "id": null,  "method": "ready",  "params": [    {      "accept": 1,      "serial": "001d50101979"    },
{
  "result": {
    "serial": "001d50101979",
    "name": "001d50101979",
    "model": "HMP200",
    "mode": "normal",
    "firmware": {
      "version": "3.2.2-1.0.28801",
      "status": "normal"
    },
    "uptime": "233.50",
    "bootid": "e62f7839-95b1-4775-8476-c0b1b5b4857f"
  },
  "error": null,
  "id": 1231
}  ] }

我正在使用以下课程

Public Class Firmware
   Public Property version As String
   Public Property status As String
End Class
Public Class Result
   Public Property serial As String
   Public Property name As String
   Public Property model As String
   Public Property mode As String
   Public Property firmware As Firmware
   Public Property uptime As String
   Public Property bootid As String
End Class
Public Class Param
   Public Property accept As Integer
   Public Property serial As String
End Class
Public Class Player
   Public Property id As Object
   Public Property method As String
   Public Property params As Param()
End Class

我没有问题反序列化根类Player,但我不确定如何反序列化Result类。

 Dim Player As New Player
 Player = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Player)(JsonString)
 Dim FirmwareVersion As String = Player.id
 Dim bootid As String = Player.method
 Dim Model As String = Player.params(0).accept
 Dim Serial As String = Player.params.ElementAt(0).serial

1 个答案:

答案 0 :(得分:2)

将您的班级Param更改为

Public Class Param
    Public Property accept As Integer
    Public Property serial As String
    Public Property result As Result
End Class

然后您就可以像{<}>那样访问result

Dim Player As New Player
Player = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Player)(JsonString)
Dim FirmwareVersion As String = Player.id
Dim bootid As String = Player.method
Dim Model As String = Player.params(0).accept
Dim Serial As String = Player.params.ElementAt(0).serial

For Each p In Player.params
    If p.result IsNot Nothing Then
        Console.WriteLine(p.result.model)
    End If
Next