Search code examples
c#jsonjson.net

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. 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.


Solution

  • 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