my json file
[
{ "name" : "student1",
"grade" : "A"
},
{ "name" : "student2",
"grade" : "B"
}
]
我的编写代码
using (FileStream fs = File.Open(WebConfigurationManager.AppSettings["JsonFileLocation"], FileMode.Append))
using (StreamWriter sw = new StreamWriter(fs))
using (JsonWriter jw = new JsonTextWriter(sw))
{
var student = new Students{name = name, grade = grade};
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, student);
}
在我写新学生之后
[
{ "name" : "student1",
"grade" : "A"
},
{ "name" : "student2",
"grade" : "B"
}
]
{ "name" : "student3",
"grade" : "C"
}
请注意它是如何追加在文件末尾而不是在最后一条记录之后和方括号内的。这使我的 json 文件无效。我该如何做到这一点,以便它将在方括号内附加新记录并带有逗号。
您正在将单个学生对象 JSON 附加到 Student 对象 JSON 数组中。请注意 [] 表示数组。
您需要读取数组,将现有学生对象附加到数组中,然后将数组写回 JSON。
下面的代码将文件中的 JSON 内容读取到 Students 对象列表中(您可能希望将类名称重命名为 Student),将新的 Students 对象追加到此列表中,然后将完整的 Students 列表写回文件中。该文件将包含 3 个正确 JSON 格式的学生对象。
var fileName = WebConfigurationManager.AppSettings["JsonFileLocation"];
List<Students> studentsList = new List<Students>();
using (var sr = new StreamReader(fileName))
{
var jsonStudentsText = sr.ReadAllText();
studentsList = JsonConvert.DeserializeObject<List<Students>>(jsonStudentsText);
}
studentsList.Add(new Students{name = name, grade = grade});
using (var sw = new StreamWriter(fileName))
{
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, studentsList);
}
}
尝试将 JSON 分解为列表,然后附加一个新对象以列出并将其塞里亚化回 JSON
List<Students> studentlist = JsonConvert.DeserializeObject<List<Students>>(your json);
studentlist.Add(new Students{name = name, grade = grade});
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(@"c:json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, studentlist);
}