如何在另一个 JObject 中循环动态 JObjects?

How to cycle for dynamic JObjects in another JObject?

实际上,我正在处理一些 JSON 数据,这些数据来自 Framework 3.5VB.NET 中旧 VB.NET 项目中的一些 API

我卡在处理以下响应中:

{
  "data": {
    "89359": {
      "name": "A",
      //...
    },
    "89360": {
      "name": "B",
      //...
    }
  }
}

数据中的每个项目都是动态的,但 API 没有将数据设置为数组,我试图从每个项目中获取数据,就像我对 JSON 数组所做的那样像这样:

Dim options As JObject = JObject.Parse(json)
For Each opt As JObject In options("data")
    MsgBox(opt("name"))
Next

但在这种情况下它不起作用,正如我所说的数据不是数组...

那么如何处理来自 JSON 的数据,因为 89359 和 89360 是动态的?

你的问题是 options("data") 声明 属于那些 JProperty 对象的 JToken while actually being of type JObject, so when you enumerate it you are actually enumerating its JProperty children. But what you need are the values 类型,这些对象在层次结构:

For Each jProperty As JProperty In options("data")
    Dim propertyName = jProperty.Name ' The "89359" names, in case you need them for some reason
    Dim opt As JObject = jProperty.Value
    Dim name As String = opt("name")  ' Cast the name to a String using the JToken implicit casting operator
    ' Use the name as required
    MsgBox(name)
Next    

演示 fiddle here.

假设具有 name 属性 的对象具有其他属性,我会做的是:

  1. 创建一个 class 来表示具有 name 的对象 属性
  2. 将传入数据反序列化为 JObject
  3. 获取 JObject 的“数据”项
  4. 从步骤 3 调用 ToObject 到字典(Of Integer,DataObject)

这是一个例子:

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()
        Dim input As String = "{""data"": {""89359"": {""name"": ""A"" }, ""89360"": {""name"": ""B"" } } }"
        Dim data = JsonConvert.DeserializeObject(Of JObject)(input)
        Dim dataItems = data.Item("data").ToObject(Of Dictionary(Of Integer, DataObject))

        For Each dataItem In dataItems
            Console.WriteLine("Key: {0}, DataObject.Name: {1}", dataItem.Key, dataItem.Value.name)
        Next
        Console.ReadLine()
    End Sub

End Module

Public Class DataObject

    Public Property name As String

    ' ...

End Class

现在对象通过 dataItems.Values 方法作为数组存在。

实例:Fiddle