如何迭代来自JsonConvert.DeserializeObject的数据?

问题描述 投票:0回答:1

我正在使用Azure函数来创建一个excel文件,但我有点难以迭代输入。

这是输入:

{
    "data": {
        "Header1": {
            "body": [
                "1",
                "2",
                "3"
            ]
        }
    }
}

我希望首先获得“数据”中对象的键并将其放在第一个顶部单元格中,但我有一点难以迭代并从中获取键。这就是我想要做的事情:

        Data data = JsonConvert.DeserializeObject<Data>(body as string);
        foreach (var item in data.data.Keys)
        {
            // For each iteration, go to the right. In this case, `i` doesn't exist.
            // Is there a way to do it then?
            Cells[0, i] = item; // Not item, the key of item.
        }

Header1只是一个例子,键可以是任何单词。

数据类:

public class Data
{
    public dynamic data { get; set; }
}
c# .net loops
1个回答
1
投票

为了更好的结构,你将不得不放弃使用动态变量并编写一些类,这是一个例子:

public class DataContainer
{

    public Dictionary<string, Header> Data { get; set; }

}

public class Header
{
    public int[] Body { get; set; }

}

你现在要做的就是像这样使用它:

string json = "{\"data\":{\"Header1\":{\"body\":[\"1\",\"2\",\"3\"]}}}";
DataContainer data = JsonConvert.DeserializeObject<DataContainer>(json);

这将为您提供一个具有正确信息的DataContainer实例,您可以像这样迭代它:

foreach (var kvp in data.Data)
{
    // kvp.Key holds the keys (Header1, etc...)
    // kvp.Value holds a Header instance
    // kvp.Value.body holds the integer array you have
}
© www.soinside.com 2019 - 2024. All rights reserved.