在 C# 中从 JSON-List 获取 property/object-name

Getting property/object-name from JSON-List in C#

我有以下 JSON- 字符串:

{"object":{"4711":{"type":"volume","owner":"john doe","time":1426156658,"description":"Jodel"},"0815":{"type":"fax","owner":"John Doe","time":1422900028,"description":"","page_count":1,"status":"ok","tag":["342ced30-7c34-11e3-ad00-00259073fd04","342ced33-7c34-11e3-ad00-00259073fd04"]}},"status":"ok"}

该数据的人类可读屏幕截图:

我想获取该数据的值“4711”和“0815”。我使用以下代码遍历数据:

JObject tags = GetJsonResponse();
var objectContainer = tags.GetValue("object");
if (objectContainer != null) {
  foreach (var tag in objectContainer) {
    var property=tag.HowToGetThatMagicProperty();
  }
}

在位置 "var property=" 我想获得值“4711”。

我可以只使用字符串操作

string tagName = tag.ToString().Split(':')[0].Replace("\"", string.Empty);

但必须有更好、更像 OOP 的方式

我用这个得到了结果

        foreach (var tag in objectContainer)
        {
            var property = tag.Path.Substring(tag.Path.IndexOf(".") + 1);
            Console.WriteLine(property);
        }
    }
    Console.ReadLine();

}

如果您明确地将 "object" 对象作为 JObject 获取,则可以访问 JObject 内每个成员的 Key 属性。当前 objectContainerJToken,不够具体:

JObject objectContainer = tags.Value<JObject>("object");

foreach (KeyValuePair<string, JToken> tag in objectContainer)
{
    var property = tag.Key;

    Console.WriteLine (property); // 4711, etc.
}

JObject 公开了 IEnumerable.GetEnumerator 的实现,其中 returns KeyValuePair<string, JToken> 包含对象中每个 属性 的名称和值。

示例: https://dotnetfiddle.net/QbK6MU