c# 利用Newtonsoft.Json 把对象序列化成json,反序列化为对象, 还有吧list对象序列化和反序列化,适用于各种对象

c# 利用Newtonsoft.Json 把对象序列化成json,反序列化为对象;

还有吧list对象序列化和反序列化,适用于各种对象,封装了一个类,方便调用

 public class ParamMng
    {
        private static ParamMng uniqueInstance;
        private static readonly object locker = new object();
        public static ParamMng GetInstance()
        {
            lock (locker)
            {
                if (uniqueInstance == null)
                {
                    uniqueInstance = new ParamMng();
                }
            }
            return uniqueInstance;
        }
        public ParamMng()
        {

        }

        public T ReadJsonConfig(string jsonPath)
        {
            StreamReader sr = File.OpenText(jsonPath);
            string jsonWordTemplate = sr.ReadToEnd();
            sr.Close();
            return JsonConvert.DeserializeObject(jsonWordTemplate);
        }

        public void WriteJsonConfig(object info, string  jsonPath)
        {
            try
            {
                string objectsJsonStr = JsonConvert.SerializeObject(info);
                File.WriteAllText(jsonPath, objectsJsonStr);
            }
            catch
            {
                Console.WriteLine("error");
            }
        }

        public List ReadJsonConfigList(string jsonPath)
        {
            StreamReader sr2 = File.OpenText(jsonPath);
            string jsonWordTemplate = sr2.ReadToEnd();
            sr2.Close();
            object o=  JsonConvert.DeserializeObject(jsonWordTemplate, typeof(List));
            List list = o as List;
            return list;
        }

        public void WriteJsonConfigList(List info, string jsonPath)
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                StringWriter sw = new StringWriter();
                serializer.Serialize(new JsonTextWriter(sw), info);
                string result = sw.GetStringBuilder().ToString();
                File.WriteAllText(jsonPath, result);
            }
            catch
            {
                Console.WriteLine("error");
            }
        }
    }

 

你可能感兴趣的:(C#)