c# - 如何使用 JSON.NET 遍历嵌套字典?

标签 c# .net 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,
                   ...
                }
            }
         }
}

我想解析这个结构,记住所有字典的键都不是我提前知道的。

这是我编写的代码(我打算在它工作后转换为 LINQ...)- 我希望它能与几个嵌套循环一起工作,但显然 JTokens 和 JObjects 不能像我那样工作以为... Id 始终为 null。

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

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

最佳答案

发现这个问题试图找出如何在 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;
    }
}

关于c# - 如何使用 JSON.NET 遍历嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967576/

相关文章:

c# - 使用 C# DataGridView 自定义选择

c# - 使用 GDI+ 重叠图像

c# - C# 任务是否在一个内核上运行?

.net - .NET CLR JIT 是否每次都编译每个方法?

asp.net - 在连续项目中构建具有不同颜色的颜色矩阵的最佳方法

json - 如何在 Inno Setup 中解析 JSON 字符串?

c# - 在 C# 中的位置拆分字符串

.net - F# Seq 的一个实现问题

javascript - Jquery 复选框选择迭代

json - 来自 Powershell 的 Mongodb Find() 查询