【问题标题】:Insert a single object into json file without rewriting entire file将单个对象插入 json 文件而不重写整个文件
【发布时间】: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 文件,而无需重写所有内容。但是,我一直在谷歌上四处寻找,并没有找到一种方法来做到这一点。有谁知道这是否可行,如果可以,在这种情况下我该如何处理?

【问题讨论】:

    标签: c# asp.net json json.net


    【解决方案1】:

    JSON 不是一种数据库格式,磁盘上的 JSON 文件只是一个平面文件,其中的数据恰好是结构化的,因此您可以将它(在内存中)视为对象。但在磁盘上,它只是一个文本文件,文件系统并不是为将数据有效地插入文件中间而设计的,正如the answers here 所建议的那样,对文件系统本身进行非常棘手的操作也是如此。

    是的,它效率低下。如果您想要效率,请使用专为更新而设计的数据库。但是,对于相对较小的 JSON 文件,如果将整个文件保存到磁盘只需几分之一秒,这种理论上的低效率可能毫无意义。

    【讨论】:

      【解决方案2】:

      不,你不能,因为序列化程序应该读取整个文件以完成构建 JSON 对象结构。 同时,这可以通过手动文本文件编辑来完成,但这种解决方案将是值得怀疑的。 如果你想快速读/写数据,也许你应该考虑另一种数据结构形式,例如,在 DB 中养马。

      【讨论】:

        猜你喜欢
        • 2015-09-24
        • 2016-01-17
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-24
        • 1970-01-01
        相关资源
        最近更新 更多