【发布时间】:2015-04-13 11:24:37
【问题描述】:
谁能告诉我如何添加新学生? 我开始学习使用 json。我试图读取、删除或重命名 json 中的某些内容。它运作良好,但我在添加新学生时遇到问题..:
StreamReader input = new StreamReader("student.txt");
string kontext = input.ReadToEnd();
input.Close();
JSONNode j = JSONNode.Parse(kontext);
Console.WriteLine("ID: ");
string c = "\"" + Console.ReadLine() + "\"";
//write to console name and surname by id
int n = j["student"].Count;
for (int i = 0; i < n; i++)
{
string temp = j["student"][i][0].ToString("");
if(c == temp)
{
Console.WriteLine(j["student"][i]["name"]);
Console.WriteLine(j["student"][i]["surname"]);
}
}
//rename by id + save to json
Console.WriteLine("ID: ");
c = "\"" + Console.ReadLine() + "\"";
for (int i = 0; i < j["student"].Count; i++)
{
string temp = j["student"][i][0].ToString("");
if (c == temp)
{
Console.Write("New name: ");
string rename = Console.ReadLine();
j["student"][i]["meno"] = rename;
StreamWriter output = new StreamWriter("student.txt");
output.WriteLine(j.ToString(""));
output.Close();
Console.WriteLine(j["student"][i]["meno"]);
}
}
//remove by id
Console.WriteLine("ID: ");
c = "\"" + Console.ReadLine() + "\"";
for (int i = 0; i < j["student"].Count; i++)
{
string temp = j["student"][i][0].ToString("");
if (c == temp)
{
j["student"].Remove(i);
StreamWriter output = new StreamWriter("student.txt");
output.WriteLine(j.ToString(""));
output.Close();
}
}
//add new student
Console.ReadKey();
}
这是我的回复
【问题讨论】:
-
您可以将您的 json 添加为代码而不是图片吗?
-
您似乎正在努力完成作业。你能说出你尝试了什么吗?
-
为什么不使用真正的 C# 对象对数据进行建模,并使用 Newtonsoft Json.net newtonsoft.com/json 之类的东西对它们进行序列化/反序列化?