Insert a single object into json file without rewr

2020-04-11 11:19发布

问题:

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

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?

回答1:

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.

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.



回答2:

No, you couldn't, because serializer should read entire file to complete building JSON object structure. At the same time, this can be done with manual text file editing, but this solution will be doubtful. If you want fast read/write access to data, maybe you should consider another data-structure forms, for example, keepeing horses in DB.