VB.NET 从 json 反序列化对象中获取键列表

VB.NET Get list of keys from json deserialized object

我想获取 json 反序列化对象中的键

json 看起来像:

{"key1":1,"key2":2,"key3":3}

我正在使用 JavaScriptSerializer :

Dim jsonStr As String = "{""key1"":1,""key2"":2,""key3"":3}"

Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(jsonStr)

Dim jQty As Integer = j.Count 'Count key/value pairs (Return 3)

现在我想获取 j 中现有键的列表。 我试过了:

Dim keys As List(Of String) = j.Properties().Select(Function(p) p.Name).ToList()

但它给了我"System.MissingMemberException: 'Public member 'Properties' on type 'Dictionary(Of String,Object)' not found.'"

默认情况下,它反序列化为 Dictionary(Of String, Object) 对象,如错误消息所述。因此,您只需要遍历字典条目列表:

For Each entry As KeyValuePair(Of String, Object) In j
    Console.WriteLine("Key = " & entry.Key)
    Console.WriteLine("Value = " & entry.Value)
Next

或者,如果您只需要键名:

j.Select(Function(entry) entry.Key)