我如何解析在C#中的JSON对象的时候,我不知道事先的关键?

问题描述:

我有一个看起来像这样的一些JSON数据:

I have some JSON data that looks like this:

{
  "910719": {
    "id": 910719,
    "type": "asdf",
    "ref_id": 7568
  },
  "910721": {
    "id": 910721,
    "type": "asdf",
    "ref_id": 7568
  },
  "910723": {
    "id": 910723,
    "type": "asdf",
    "ref_id": 7568
  }
}

如何解析这个使用JSON.net?我可以先做到这一点:

How can I parse this using JSON.net? I can first do this:

JObject jFoo = JObject.Parse(data);

我需要能够对每个对象遍历该列表中。我希望能够做这样的事:

I need to be able to iterate over each object in this list. I would like to be able to do something like this:

foreach (string ref_id in (string)jFoo["ref_id"]) {...}

foreach (JToken t in jFoo.Descendants())
{
    Console.WriteLine((string)t["ref_id"]);
}

,但当然不工作。所有的例子都工作很好,如果你知道键,同时写你的code。它打破了,当你不知道事先的关键。

but of course that doesn't work. All the examples work great if you know the key while writing your code. It breaks down when you don't know the key in advance.

这是可行的;这个工作,但它不是优雅。我敢肯定有一个更好的办法。

It's doable; this works but it's not elegant. I'm sure there's a better way.

var o = JObject.Parse(yourJsonString);

foreach (JToken child in o.Children())
{
    foreach (JToken grandChild in child)
    {
        foreach (JToken grandGrandChild in grandChild)
        {
            var property = grandGrandChild as JProperty;

            if (property != null)
            {
                Console.WriteLine(property.Name + ":" + property.Value);
            }
        }
    }
}

打印:

id:910719
type:asdf
ref_id:7568
id:910721
type:asdf
ref_id:7568
id:910723
type:asdf
ref_id:7568