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();

                }
            }

        }
 
    }
}

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source