使用C#获取JSON.NET中的属性名称

时间:2014-01-19 06:32:49

标签: c# json linq json.net

我一直在编写一个Minecraft发射器供我个人使用(source)。我已经到了需要解析包含官方发射器已经制作的所有可用“配置文件”的JSON文件的地步。它看起来像这样:

{
  "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
    },

正如您所看到的,有一个名为“profiles”的对象,其中有一些带有变量名称的属性。我想获取这些属性的名称,而不是它们的值。我不知道该怎么做,我试过Value或只是简介.ToString(),但两个结果都给了我属性本身的内容,而不是它的名字。有没有办法得到这些名字?
编辑:解析配置文件JSON的代码是:

    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());
    }

2 个答案:

答案 0 :(得分:2)

使用Name property

  

获取属性名称。

     

public string Name { get; }

MessageBox.Show(profileAvail.Name);

答案 1 :(得分:0)


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


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