Search code examples
c#jsonlinqjson.net

Get Key Name from nested json object


I am new to C# and JSON and need some help in getting the Key name(s) in a list of a nested JSON object. The keys are dynamic so I won't necessarily know the keys.

sample code I've tried.

protected void test()
{
        var mystring = @"{
          ""zone1"": {
            ""sites"": {
              ""site1"": {
                ""to"": ""email1"", 
                ""subject"": ""subjecttxt"", 
                ""link"": ""somesite""
            },
            ""site2"": {
              ""to"": ""email1"", 
              ""subject"": ""subject"",
              ""link"": ""somesite""
            }
          }, 
          ""zone2"": {
            ""to"": ""email1"", 
            ""subject"": ""subject"", 
            ""link"": ""somelink""
          }}";
        var rss = JObject.Parse(mystring);

        foreach (var section in rss)
        {
            Console.Write(section.Key);
            IList<JToken> result = rss["zone1"]["sites"].Children().ToList();
            var zone = section.Key;
            var site = rss[zone]["sites"];
            foreach (var subsite in rss["zone1"]["sites"])
            {
                var subs = subsite.Parent.ToString();
                // some other code
            }
         }
}

Looking for a result:

site1,
site2,
...

I can get the children as IList but looking for something similar to "section.Key" as noted above.


Solution

  • I believe what you are looking for is to get the properties of the sites. Since accessing the rss["zone1"]["sites"] returns a JToken, you will need to convert that to JObject and then use Properties() method to get the data you need.

    var sites = ((JObject)rss["zone1"]["sites"]).Properties();
    

    Then you can simply iterate over the IEnumerable<Jproperty> to get the Name of the property or whatever else you need from under it.

    To get the section.Key for the sites, you can use the following code.

    foreach(var site in (JObject)rss["zone1"]["sites"]) {
        Console.WriteLine(site.Key);
    }
    

    Output:

    site1
    site2