VB.NET使用JObject从嵌套的JSON值返回值

时间:2017-12-22 22:26:29

标签: json vb.net

我正在尝试使用VB.NET专门使用JObject从JSON字符串返回嵌套值。我可以从第一级的项中获取值,但无法弄清楚如何获取其中一个嵌套值。

例如,在下面的示例JSON中,我如何能够获得Mike的年龄并循环遍历所有值,包括嵌套的值?

这是我的JSON

{ 
    "name": "John Doe", 
    "age": 36, 
    "address": [ 
        { "street": "1234 Somewhere Avenue", "city": "Los Angeles", "state": "CA" } 
    ], 
    "children": [ 
        { "name": "Mike", "age": "12" }, 
        { "name": "Emma", "age": "10" } 
    ] 
}

以下是一些示例代码:

Imports Newtonsoft.Json.Linq

Partial Class TestJObject
    Inherits System.Web.UI.Page

    Sub Test_JObject()
        Dim sJson As String = MyJsonStringFromAbove

        Dim myObj As JObject = JObject.Parse(sJson)

        'How do I get to Mike's age?
        Response.Write(myObj.Property("children").ToString & "<br>")

        'How do I loop though the nested values?.
        For Each myProp As JProperty In myObj.Properties
            Response.Write(myProp.Name.ToString & " - " & myProp.Value.ToString & "<br>")
        Next
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

试试这个:

Dim data As String = "{ 
                                'name': 'John Doe', 
                                'age': 36, 
                                'address': [ 
                                    { 'street': '1234 Somewhere Avenue', 'city': 'Los Angeles', 'state': 'CA' } 
                                ], 
                                'children': [ 
                                    { 'name': 'Mike', 'age': '12' }, 
                                    { 'name': 'Emma', 'age': '10' } 
                                ] 
                            }"

    Dim obj As JObject = JObject.Parse(data)
    Dim children As JArray = obj("children")
    For Each child As JObject In children
        Console.WriteLine("NAME: {0}  /   AGE: {1}", child("name"), child("age"))
    Next