插入一个对象转换成JSON文件而无需重写整个文件 [英] Insert a single object into json file without rewriting entire file

查看:121
本文介绍了插入一个对象转换成JSON文件而无需重写整个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON.NET一匹马对象添加到马匹的JSON格式的数据库的方法。一种选择是将整个文件反序列化为马列表,添加新的坐骑,那么序列化的列表,并改写整个文件。我实现了在下面的code这种做法。

I'm working on a method that uses JSON.NET to add a horse object to a JSON-formatted database of horses. One option is to deserialize the entire file into a list of horses, add the new horse, then serialize the list and rewrite the whole file. I've implemented this approach in the code below.

    // 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;
    }

虽然这个工作,它似乎效率不高给我。理想情况下,我可以简单地插入新马对象到JSON文件而无需重写一切。不过,我一直在谷歌上环顾四周,并没有发现一种方法来做到这一点。有谁知道这是可能的,如果是这样,我怎么可能会接近它在这种情况下?

While this works, it seems inefficient to me. Ideally, I could simply insert the new horse object into the JSON file without rewriting everything. However, I've been looking around on google and haven't found a way to do this. Does anyone know if this is possible, and if so, how I might approach it in this case?

推荐答案

JSON是不是数据库的格式,并在磁盘上的JSON文件仅仅是数据平面文件恰好是结构化的,它允许你把它 - 内存 - 为对象。但在磁盘上,它只是一个文本文件,和文件系统不是设计用于数据的有效插入到文件的中间,没有文件系统本身的非常棘手的操作,如<一href=\"http://stackoverflow.com/questions/2398129/writing-to-the-middle-of-the-file-without-overwriting-data\">the答案在这里建议。

JSON isn't a database format, and a JSON file on disk is just a flat file with data that happens to be structured, which allows you to treat it - in memory - as objects. But on disk, it's just a text file, and filesystems are not designed for efficient insertion of data into the middle of a file, not without very tricky manipulation of the filesystem itself, as the answers here suggest.

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

Yes, it is inefficient. If you want efficiency, use a database that's designed for updates. However, for relatively small JSON files, this theoretical inefficiency may be meaningless if saving the entire file to disk takes a fraction of a second.

这篇关于插入一个对象转换成JSON文件而无需重写整个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆