Ilan
Ilan

Reputation: 513

Getting names of properties in JSON.NET with C#

I've been coding a Minecraft launcher for my personal use (source). I've gotten to the point where I need to parse a JSON file containing all available "profiles" already made by the official launcher. It looks like this:

{
  "profiles": {
    "1.6.2": {
      "name": "1.6.2",
      "gameDir": "C:\\Users\\Ilan\\AppData\\Roaming\\.ilan\\1.6.2mc",
      "lastVersionId": "1.6.2",
      "allowedReleaseTypes": [
        "snapshot",
        "release"
      ],
      "playerUUID": "e2f423057b72487eb6f7f8ce877a8015"
    },
    "1.6.1": {
      "name": "1.6.1",
      "gameDir": "C:\\Users\\Ilan\\AppData\\Roaming\\.ilan\\1.6.1",
      "lastVersionId": "1.6.1"
    },
    "13w38c": {
      "name": "13w38c",
      "lastVersionId": "13w38c",
      "javaArgs": "-Xmx1G",
      "allowedReleaseTypes": [
        "snapshot",
        "release"
      ],
      "playerUUID": "e2f423057b72487eb6f7f8ce877a8015",
      "useHopperCrashService": false
    },

As you can see, there is an object called "profiles" and in it there are properties with variable names. I want to get the names of those properties, not their values. I don't know how to do so, I tried Value or just the profile .ToString() but both results give me the contents of the property itself, not the name of it. Is there a way to get the names?
Edit: the code that parses the profile JSON is:

    string profileJSON = File.ReadAllText(Variables.profileJSONFile);
    JObject profiles = JObject.Parse(profileJSON);
    MessageBox.Show(profiles["profiles"].ToString());
    foreach (JProperty profileAvail in profiles["profiles"])
    {
        MessageBox.Show(profileAvail.ToString());
    }

Upvotes: 0

Views: 196

Answers (2)

Dibu
Dibu

Reputation: 891


   IDictionary< string, JToken > json = Jobject.Parse( strJson );


   foreach (var kv in json) 
     {
        Console.WriteLine( kv.Key );
     }

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

Use Name property:

Gets the property name.

public string Name { get; }

MessageBox.Show(profileAvail.Name);

Upvotes: 2

Related Questions