我正在创建软件,用户可以创建和加载配置文件来填充文本框。概要文件中包含的名称和其他信息存储在一个JSON文件中。配置文件名称可以包含用户输入的任何文本。因此,我尝试获取每个对象的JSON文件名(=每个配置文件名),以便在treeview中显示它们,但我得到的只是它们的内容。
我有一个包含两个对象的JSON文件:
[
{
"profile1": {
//Some informations 1
},
"profile2": {
//Some informations 2
}
}
]
目前,我有代码允许我获取给定标记的值,但我找不到一种方法来获取每个对象的名称:
using (StreamReader r = File.OpenText(path))
{
string json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
debug_tb.Text += item.profile1; //Gives me each values of the "profile1 object"
}
}
所以我试图得到的是显示"profile1“、"profile2”和"profile3“,如果它存在的话。
发布于 2019-07-10 03:02:35
您的问题是JSON是一个只有一个对象的数组。所以你可以先简化JSON:
{
"profile1": {
//Some informations 1
},
"profile2": {
//Some informations 2
}
}
然后,您就可以轻松地遍历JSON中的每一项并获得它的Name
。
dynamic array = JsonConvert.DeserializeObject("{ \"profile1\": { }, \"profile2\": { } }");
foreach (var item in array)
{
debug_tb.Text += item.Name; //Gives the name of the object
}
Console.WriteLine(text);
Console.ReadLine();
https://stackoverflow.com/questions/56958756
复制相似问题