【问题标题】:VB.NET Get list of keys from json deserialized objectVB.NET 从 json 反序列化对象中获取键列表
【发布时间】:2017-07-18 22:42:27
【问题描述】:

我想获取 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: '未找到类型'Dictionary(Of String,Object)' 上的公共成员'Properties'。'”

【问题讨论】:

    标签: json dictionary keyvaluepair


    【解决方案1】:

    默认情况下,它会反序列化为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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-16
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 2017-10-28
      • 2011-12-28
      相关资源
      最近更新 更多