如何使用JSON.NET迭代嵌套字典?

Tyl*_*ler 5 .net c# json json.net

我有一个JSON结构,我想使用JSON.NET手动解析为POCO对象.

JSON结构是一堆嵌套字典...根字典包含类别,下一级包含这些类别中的产品,最后一级包含这些产品的版本.

{
        "category-1": {
           "product-1": {
              "product-version-1": {
                   "id":1,
                   ...
               }
            }
        },
        "category-2": {
           "product-2": {
              "product-version-2": {
                   "id":2,
                   ...
               }
            },
            "product-3": {
               "product-version-3": {
                   "id":3,
                   ...
                }
            }
         }
}
Run Code Online (Sandbox Code Playgroud)

我想解析这个结构,记住所有词典的关键是我不知道的.

这是我写的(我要转换为LINQ一旦它的工作...)的代码 - 我想到这与一对夫妇嵌套循环的工作,但显然JTokens和JObjects不工作我以为的方式.. .Id始终为空.

var productsJObject = JObject.Parse(result.Content.ReadAsStringAsync().Result);

foreach (var category in productsJObject)
{
    foreach (var product in category.Value)
    {
        foreach (var version in product)
        {
            var poco = new Poco
                      {
                          Id = version.SelectToken("id").ToString()
                      };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,如何使用JSON.Net迭代嵌套字典?

hro*_*oss 7

发现这个问题试图弄清楚如何在C#中解析JSON.NET.希望我的回答能帮助别人......

我写了这段代码来帮助我解析一个随机的JSON对象并分析结构.它有些粗糙,可能无法处理所有场景,但它可以解决问题.现在它只是在字典中存储位置,但它应该很容易看到它做了什么,并修改它来做你想要的:

static void Main(string[] args)
{
    Dictionary<string, string> nodes = new Dictionary<string, string>();

    // put your JSON object here
    JObject rootObject = JObject.Parse("{\"world\": {\"hello\": \"woo\", \"foo\": \"bar\", \"arr\": [\"one\", \"two\"]}}");

    ParseJson(rootObject, nodes);

    // nodes dictionary contains xpath-like node locations
    Debug.WriteLine("");
    Debug.WriteLine("JSON:");
    foreach (string key in nodes.Keys)
    {
        Debug.WriteLine(key + " = " + nodes[key]);
    }
}

/// <summary>
/// Parse a JSON object and return it as a dictionary of strings with keys showing the heirarchy.
/// </summary>
/// <param name="token"></param>
/// <param name="nodes"></param>
/// <param name="parentLocation"></param>
/// <returns></returns>
public static bool ParseJson(JToken token, Dictionary<string, string> nodes, string parentLocation = "")
{
    if (token.HasValues)
    {
        foreach (JToken child in token.Children())
        {
            if (token.Type == JTokenType.Property)
                parentLocation += "/" + ((JProperty)token).Name;
            ParseJson(child, nodes, parentLocation);
        }

        // we are done parsing and this is a parent node
        return true;
    }
    else
    {
        // leaf of the tree
        if (nodes.ContainsKey(parentLocation))
        {
            // this was an array
            nodes[parentLocation] += "|" + token.ToString();
        }
        else
        {
            // this was a single property
            nodes.Add(parentLocation, token.ToString());
        }

        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)