Using JSON as a datastore in C#

Shapes
Image by Gerd Altmann from Pixabay

For some not too complex applications, JSON can be a very handy way to store data rather than say using a database. It also has the advantage of storing data of varying sizes. For instance Lists with varying numbers of items. I created a Saveable generic class below that you use as an ancestor class for that you wish to Save/Load an IList of whatever.

 

 

    public class SaveAble<T>
    {
        private string _error = "";
        string LastError()
        {
            return _error;
        }
        public IList<T>? Load(string filePath)
        {
            if (!File.Exists(filePath))
            {
                Log.Error("Missing file {filePath}");
                _error = $"Missing file {filePath}";
                return null;
            }

            var content = File.ReadAllText(filePath);
            if (string.IsNullOrEmpty(content))
            {
                Log.Error("{filePath} file is empty");
                _error=$"{filePath} file is empty";
                return null;
            }

            return JsonSerializer.Deserialize<IList<T>>(content, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            })!;
        }

        public bool Save(string filename,IList<T> collection)
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
                PropertyNameCaseInsensitive = true
            };
            try
            {
                var bytes = JsonSerializer.SerializeToUtf8Bytes(collection, options);
                File.WriteAllBytes(filename, bytes);
                return true;
            }catch (Exception ex)
            {
                _error = $"Exception:{ex.Message}";
                return false;
            }
        }

    }

Just define your class MyClasses from SaveAble<MyClass>

where MyClass is the class you have a List of. Then you can do

MyClasses myclasses;
myclasses.Save("filename",List<MyClass>) and

List<MyClass> list = myclasses.Load("filename");

It is fast. On my PC (now six years old), it can load a 99,000 line JSON file in well under a second.

(Visited 15 times, 1 visits today)