【问题标题】:Loop through all the properties in a Dynamic JSON object from Clientside in VB.NET从 VB.NET 的客户端循环遍历动态 JSON 对象中的所有属性
【发布时间】:2015-12-08 11:43:45
【问题描述】:

我有一个如下的 JSON 对象,大多数情况下它没有特定的结构。这是使用 jquery 从客户端创建并通过 AJAX 发送到服务器端的。

{
    "items": {
        "1": [{
            "text": "Man",
            "itemID": "1",
            "checked": 1,
            "sequence": 1,
            "matchingtext": "",
            "weight": 0
        }, {
            "text": "goat",
            "itemID": "2",
            "checked": 0,
            "sequence": 2,
            "matchingtext": "",
            "weight": 0
        }, {
            "text": "dog",
            "itemID": "3",
            "checked": 0,
            "sequence": 3,
            "matchingtext": "",
            "weight": 0
        }],
        "2": [{
            "text": "pizza",
            "itemID": "1",
            "checked": 1,
            "sequence": 1,
            "matchingtext": "",
            "weight": 0
        }, {
            "text": "horse",
            "itemID": "2",
            "checked": 0,
            "sequence": 2,
            "matchingtext": "",
            "weight": 0
        }, {
            "text": "paper",
            "itemID": "3",
            "checked": 0,
            "sequence": 3,
            "matchingtext": "",
            "weight": 0
        }]
    },
    "wbmode": "dd",
    "wbanswertype": "sc"
}

由于它没有任何特定的结构,我无法使用某些结构化类对其进行反序列化。

那么我怎样才能遍历 items 的所有对象,例如在这种情况下 1 和 2

【问题讨论】:

  • 创建 json 等价的强类型类,并使用 JSON.Net 反序列化它。访问 www.json2csharp.com 以生成您的实体。
  • @Amit - 他说他不能创建具体的类,链接也坏了 - 你不需要 www!

标签: asp.net json vb.net


【解决方案1】:

我建议使用JSON.NET 库(可通过 NuGet 获得)。在您的项目中添加对它的引用并将库导入您的类后,您可以像这样遍历 JSON 结构:

    Dim jsonString = "{""items"":{""1"":[{""text"":""Man"",""itemID"":""1"",""checked"":1,""sequence"":1,""matchingtext"":"""",""weight"":0},{""text"":""goat"",""itemID"":""2"",""checked"":0,""sequence"":2,""matchingtext"":"""",""weight"":0},{""text"":""dog"",""itemID"":""3"",""checked"":0,""sequence"":3,""matchingtext"":"""",""weight"":0}],""2"":[{""text"":""pizza"",""itemID"":""1"",""checked"":1,""sequence"":1,""matchingtext"":"""",""weight"":0},{""text"":""horse"",""itemID"":""2"",""checked"":0,""sequence"":2,""matchingtext"":"""",""weight"":0},{""text"":""paper"",""itemID"":""3"",""checked"":0,""sequence"":3,""matchingtext"":"""",""weight"":0}]},""wbmode"":""dd"",""wbanswertype"":""sc""}"

    Dim j As JObject = JObject.Parse(jsonString)

    For Each item As JProperty In j.Item("items")
        Dim itemObjects As JToken = item.Value
        For Each i As JObject In itemObjects
            For Each p In i
                Debug.Print(p.Key.ToString & " = " & p.Value.ToString)
            Next
        Next
    Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2018-09-26
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多