如何从嵌套在json数组中的对象访问数据

时间:2017-07-20 17:07:11

标签: arrays json vb.net javascriptserializer

我需要访问嵌套的json对象数组中的数据,以便能够使用vb.net 4.0中的javascriptserializer进一步操作它。

这是示例字符串:

json: {"multicast_id":216,"success":3,"failure":3,"canonical_ids":1,"results":[{"message_id":"1:0408"},{"errord":"Unavailable"}]}

这是我迄今为止编写的代码:

Class main
Public Property multicast_id As Integer
Public Property success As Integer
Public Property failure As Integer
Public Property canonical_ids As Integer
Public Property results As Results()
End Class

Class Results
Public Property message_id As String
Public Property errord As String
End Class


Public Class Form1

Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
    Dim json As String
    json = txtInsert.Text

    Try
        Dim ser As JavaScriptSerializer = New JavaScriptSerializer()
        Dim exmp As main = New main
        exmp = ser.Deserialize(Of main)(json)

        Console.WriteLine(exmp.canonical_ids)
        Console.WriteLine(exmp.multicast_id)

        For Each item As Object In exmp.results
            For Each example As String In item
                Console.WriteLine("example")
            Next
        Next

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub
End Class

我在每个语句的内部都收到错误。如果有人能帮我解决这个问题,我真的很感激。

2 个答案:

答案 0 :(得分:0)

你不需要内心的For Each。您已经使用第一个循环旋转数组。您也可以更具体地了解循环中的类型:

    For Each item As Results In exmp.results
        Console.WriteLine(item.message_id & " : " & item.errord)
    Next

答案 1 :(得分:0)

您正确获取嵌套对象。

相反,您的问题是,一旦获得该嵌套对象,您就会尝试使用For Each来获取该结果的每个字符串属性。那是无效的。

例如,这不起作用,因为Results未实现IEnumerable,因此您无法使用For Each

Dim r as new Results();
r.message_id = "1:0408"
r.errord = "Unavailable"
For Each example As String In r ' <- this will throw an error
Next

在您引用Results后,您需要按属性名称访问它:

For Each item As Results In exmp.results
    Console.WriteLine("message_id: {0}", item.message_id)
    Console.WriteLine("errord: {0}", item.errord)
Next

如果需要按名称访问属性,请将结果更改为其他类型。

例如,您可以将结果定义为Dictionary(of String, Object)的数组,如下所示:

Class main
    Public Property multicast_id As Integer
    Public Property success As Integer
    Public Property failure As Integer
    Public Property canonical_ids As Integer
    Public Property results As Dictionary(Of String, Object)()
End Class

然后你可以使用:

For Each item As Object In exmp.results 'item will be a Dictionary(Of String, Object)
    For Each example As Object In item ' example will be a KeyValuePari(Of String, Object)
        Console.WriteLine(example.key)
        Console.WriteLine(example.value)
    Next
Next

或者这样的名字:

    For Each item As Object In exmp.results 'item will be a Dictionary(Of String, Object)
        Console.WriteLine(item("message_id"))
        Console.WriteLine(item("errord"))
    Next
Next