I have a json object, a string, that contains some properties and their values. Say I never know what comes in my json object, how can I loop though it and get what properties it contains? For example:
{ "aaaa": 1, "bbbb": "qwerty", "ccc": 21.22 }
How do I collect aaa, bbb and ccc? Once again, I don't want their values, I just want the name of the properties.
CodePudding user response:
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
CodePudding user response:
Deserialize the json to Dictionary
using JsonConvert
Note: This will work if the key are always unique
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
Console.WriteLine($"{string.Join(",", result.Keys)}");
CodePudding user response:
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);