【发布时间】:2015-10-24 18:30:12
【问题描述】:
我正在研究一种使用 JSON.NET 将马对象添加到 JSON 格式的马数据库的方法。一种选择是将整个文件反序列化为马列表,添加新马,然后序列化列表并重写整个文件。我已经在下面的代码中实现了这种方法。
// adds a horse to the db
public int AddHorse(Horse horse)
{
// identify and assign next available id to horse
var horses = GetAllHorses();
int nextId = horses.Max(h => h.ID) + 1;
horse.ID = nextId;
// Add horse to list
horses.Add(horse);
// Write entire list to JSON file. Can I just insert one new horse into the file?
using (FileStream fs = File.Open(_jsonHorseDbFilePath, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fs))
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(jw, horses);
}
return nextId;
}
虽然这可行,但对我来说似乎效率低下。理想情况下,我可以简单地将新的 horse 对象插入 JSON 文件,而无需重写所有内容。但是,我一直在谷歌上四处寻找,并没有找到一种方法来做到这一点。有谁知道这是否可行,如果可以,在这种情况下我该如何处理?
【问题讨论】: