循环遍历json对象时出现意外结果

时间:2014-01-30 22:02:33

标签: json vb.net parsing variables if-statement

我有一个小应用程序,它会对api进行http调用以检索资源统计信息。 我收到类似的JSON响应:

    { "listcapacityresponse" : { "count":6 ,"capacity" : [  {"type":6,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":45660766208,"capacitytotal":106308304896,"percentused":"42.95"}, {"type":8,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":5,"capacitytotal":18,"percentused":"27.78"}, {"type":5,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":3,"capacitytotal":12,"percentused":"25"}, {"type":3,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":90202701824,"capacitytotal":1099511627776,"percentused":"8.2"}, {"type":1,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":1500,"capacitytotal":52800,"percentused":"2.84"}, {"type":0,"zoneid":"f26c2094-f2ca-4951-9265-a3f036e7f045","zonename":" CloudPlatform 1","capacityused":1476395008,"capacitytotal":97078222080,"percentused":"1.52"} ] } }

基本上,有6种类型的资源:

0内存使用情况 1 CPU使用率 3主存储 5管理IP 6二级存储 8个共享网络IP

我正在解析这样的JSON:

    Dim dtoObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of RootObject)(resourceusageresponse)
        For Each resource As Capacity In dtoObj.listcapacityresponse.capacity

    If resource.type = 0 Then
                Dim memoryusedpercent As String = resource.percentused
            ElseIf resource.type = 1 Then
                Dim cpuusedpercent As String = resource.percentused
            ElseIf resource.type = 3 Then
                Dim pristorageusedpercent As String = resource.percentused
            ElseIf resource.type = 5 Then
                Dim mgmtippercent As String = resource.percentused
            ElseIf resource.type = 6 Then
                Dim secstoragepercent As String = resource.percentused
            ElseIf resource.type = 8 Then
                Dim guestippercent As String = resource.percentused
            End If

        Next

我希望if语句中的每个变量在完成解析后都会被填充(我现在只对百分比感兴趣),但我只是得到空变量而没有错误。

我错过了一些明显的东西吗?

我不顾一切地关闭了我的项目,这是阻碍我的最后一件事!

任何帮助appriciated! :)

1 个答案:

答案 0 :(得分:0)

变量将超出If语句范围。将它们调到环路上方,你应该没问题。