【问题标题】:Getting names of properties in JSON.NET with C#使用 C# 获取 JSON.NET 中的属性名称
【发布时间】:2014-01-19 06:32:48
【问题描述】:

我一直在编写 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());
    }

【问题讨论】:

标签: c# json linq json.net


【解决方案1】:

使用Name property:

获取属性名称。

public string Name { get; }

MessageBox.Show(profileAvail.Name);

【讨论】:

    【解决方案2】:
    IDictionary json = Jobject.Parse(strJson); foreach(json中的var kv) { Console.WriteLine(kv.Key); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2018-11-16
      • 2014-07-22
      • 1970-01-01
      相关资源
      最近更新 更多