简体   繁体   English

如何在 json object 中获取所有属性的名称(没有它们的值)?

[英]How to get the names of all properties (without their values) in a json object?

I have a json object, a string, that contains some properties and their values.我有一个 json object,一个包含一些属性及其值的字符串。 Say I never know what comes in my json object, how can I loop though it and get what properties it contains?假设我永远不知道我的 json object 中有什么,我该如何循环它并获取它包含的属性? For example:例如:

{ "aaaa": 1, "bbbb": "qwerty", "ccc": 21.22 } {“aaaa”:1,“bbbb”:“qwerty”,“ccc”:21.22 }

How do I collect aaa, bbb and ccc?我如何收集aaa、bbb和ccc? Once again, I don't want their values, I just want the name of the properties.再一次,我不想要它们的值,我只想要属性的名称。

It's as simple as this:就这么简单:

var json = @"{ ""aaaa"": 1, ""bbbb"": ""qwerty"", ""ccc"": 21.22 }";
var jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
var names = jobject.Root.Cast<JProperty>().Select(x => x.Name).ToArray();

That gives:这给出了:

aaaa
bbbb
ccc

Deserialize the json to Dictionary using JsonConvert使用JsonConvert将 json 反序列化为Dictionary

Note: This will work if the key are always unique注意:如果密钥始终是唯一的,这将起作用

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Console.WriteLine($"{string.Join(",", result.Keys)}");

just in one line就在一行

IEnumerable<string> names = JObject.Parse(json).Properties().Select(x => x.Name);

this will include the names of nested objects properties这将包括嵌套对象属性的名称

IEnumerable names = JObject.Parse(json).Descendants().OfType<JProperty>()
                                                           .Select(x => x.Name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM