How can I get a list of keys from Json.NET?

C#json.net

C# Problem Overview


I'm using C# and Json.NET. If I have a JObject, I want a list of the keys within the object, similar to how object.Keys() returns the keys within the object. This seems like it'd be obvious, but I'm having a rough time finding a way to do this.

Edit: I'm traversing through the object, and I want to spit out all the keys in the object as I go through. I realize that this example will result in seeing the same key multiple times, and that's OK for my needs.

public void SomeMethod(JObject parent) {
	foreach (JObject child in parent.Children()) {
		if (child.HasValues) {
		//
		// Code to get the keys here
		//
		SomeMethod(child);
		}
	}
}

C# Solutions


Solution 1 - C#

IList<string> keys = parent.Properties().Select(p => p.Name).ToList();

Documentation: JObject.Properties

Solution 2 - C#

From https://stackoverflow.com/questions/14161615/converting-a-json-net-jobjects-properties-tokens-into-dictionary-keys?rq=1

You can simply convert the JObject into a Dictionary object and access the method Keys() from the Dictionary object.

Like this:

using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, string>>();

You can now access those keys via the dictObj.Keys() method. You can see if a key exists by performing dictObj.ContainsKey(keyName) also.

Obviously, you can format the Dictionary however you want (could be Dictionary<string, object>, etc.).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - C#James Newton-KingView Answer on Stackoverflow
Solution 2 - C#Blairg23View Answer on Stackoverflow