text.json c# code example

Example: c# JsonIO

namespace JsonHelper
{

    public static class JsonIO
    {
        private static object mutex = new object();
        public static Dictionary<string,object> LockList = new Dictionary<string,object>();
        public static T CastJsonToObject<T>(this string jsonstr) where T : new()
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonstr);
            }
            catch(Exception ex)
            {
                return new T();
            }  
        }
        private  static object GetLock(string text)
        {
            lock(mutex)
            {
                if (!LockList.ContainsKey(text))
                {
                    LockList[text] = new object();
                }
                foreach (string key in LockList.Keys.ToList<string>())
                {
                    if (!key.Equals(text) && !Monitor.IsEntered(LockList[key]))
                    {
                        LockList.Remove(key);
                    }
                }
            }
            return LockList[text];
        }
        public static T Load<T>(string path) where T:new()
        {
            if (File.Exists(path))
            {
                string fullpath = Path.GetFullPath(path);      
                lock(GetLock(fullpath))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {

                        using (StreamReader sr = new StreamReader(fs))
                        {
                            string s = sr.ReadToEnd();
                            fs.Close();
                            try
                            {
                                return JsonConvert.DeserializeObject<T>(s);
                            }
                            catch
                            {
                                JsonIO.Save(path, new T());
                                return new T();
                            }

                        }

                    }
                }
                
            }
            else
            {
                JsonIO.Save(path, new T());
                return new T();
            }

        }
        public static void SetDefaultSerializer()
        {
            JsonConvert.DefaultSettings = (() =>
            {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new StringEnumConverter { });
                return settings;
            });
        }


        public static void Save(string path, object cfg)
        {
            string fullpath = Path.GetFullPath(path);
            lock (GetLock(fullpath))
            {
                AutoResetEvent autoResetEvent = new AutoResetEvent(false);
                //We dont user Directory.CreateDirectory due. When str is "C:\config.json" it will create config.json as dir
                DirHelper.CreateDirectory(path);
                try
                {
                    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                    {

                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            sw.Write(JsonConvert.SerializeObject(cfg, Formatting.Indented));

                        }
                        fs.Close();
                    }

                }
                catch (Exception ex)
                {
                    var fileSystemWatcher =
                    new FileSystemWatcher(Path.GetDirectoryName(path))
                    {
                        EnableRaisingEvents = true
                    };

                    fileSystemWatcher.Changed +=
                        (o, e) =>
                        {
                            if (Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                            {
                                try
                                {
                                    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                                    {

                                        using (StreamWriter sw = new StreamWriter(fs))
                                        {
                                            sw.Write(JsonConvert.SerializeObject(cfg, Formatting.Indented));

                                        }
                                        fs.Close();
                                    }
                                }
                                catch (Exception ex2)
                                {

                                }


                                autoResetEvent.Set();
                            }
                        };

                    autoResetEvent.WaitOne();

                }
            }

        }
 
    }
}