我的json文件
[
{ "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文件无效。如何制作它以便在方括号内添加新记录并使用逗号。
答案 0 :(得分:3)
您将一个学生对象JSON附加到Student对象Json数组中。注意[]表示数组。
您需要读取数组,将现有的student对象追加到数组中,并将数组写回JSON。
下面的代码将文件中的JSON内容读入Students对象列表(您可能希望将类名重命名为Student),将新的Students对象附加到此列表,然后将完整的Student列表写回文件。该文件将以适当的JSON格式包含3个学生对象。
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);
}
}
答案 1 :(得分:1)
尝试dessiarilize 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);
}