我正在阅读
形式的文件[name, age]
所以我在循环中解析每一行,我想保存每一行的所有数据。 我的想法是使用词典列表
var testData = new List<Dictionary<string, string>>();
所以最终会有类似的东西
{{Name: John; Age: 30},{Name: Doe; Age: 36}}
但我不确定该怎么做。尝试将值添加到testData
:
testData[0]["Name"] = "John";
不正确。如何在C#中实现这种数据结构?
答案 0 :(得分:4)
您的第一个假设是好的:您需要使用List<Dictionary<string, string>>();
。
但是,您不能简单地使用索引器分配值。您需要添加项目到字典。
请尝试以下代码:
var testData = new List<Dictionary<string, string>>();
testData.Add(new Dictionary<string, string>
{
{"Name", "John"},
{"Age", "30"} // Note: Age is a string, and will result in "Age": "30"
});
testData.Add(new Dictionary<string, string>
{
{"Name", "Doe"},
{"Age", "36"}
});
JsonConvert.SerializeObject(testData);
或者您可以使用对象初始值设定项:
var testData = new List<Dictionary<string, string>>
{
new Dictionary<string, string>
{
{ "Name", "John" },
{ "Age", "30" }
},
new Dictionary<string, string>
{
{ "Name", "Doe" },
{ "Age", "36" }
}
};
JsonConvert.SerializeObject(testData);
另一个选项是来创建一个代表你的模型的类。对我来说,如果你的文件总是代表相同的模型(人物),它看起来是一个更好的解决方案:
public class Person
{
public string Name { get; set; }
public int Age { get; set; } // Note: Age is an int, and will result in "Age": 30
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
List<Person> testData = new List<Person>();
testData.Add(new Person("John", 30));
testData.Add(new Person("Doe", 36));
JsonConvert.SerializeObject(testData);
答案 1 :(得分:1)
我可以推荐使用Newtonsoft Json Serializer。 根据我的经验,它很容易使用。
创建一个包含2个属性的类(根据您的示例):名称和年龄。
class NamesAges
{
public string Name { get; set; }
public int Age { get; set; }
}
然后从您的文件加载到列表中(字典在这里似乎是多余的)。 我们假设这是列表:
var namesAges = new List<NamesAges>
{
new NamesAges {Name = "Abi", Age = 5},
new NamesAges {Name = "Jhon", Age = 15},
new NamesAges {Name = "Doe", Age = 20}
};
然后您需要做的就是:
var json = JsonConvert.SerializeObject(namesAges);
你得到:
[{"Name":"Abi","Age":5},{"Name":"Jhon","Age":15},{"Name":"Doe","Age":20}]
&#13;
您可以在此处找到您想要的内容:http://www.newtonsoft.com/json/help/html/SerializeObject.htm