.net JSON 序列化和反序列化,引用Newtonsoft.Json,Dll

一、将对象Object序列化成Json字符串,以便保存到数据库

  private ModelSettings GenerateModelSettings(List list)
        {
            ModelSettings model = new ModelSettings();
            model.Name = list.First().MacroLoadingStyle.ToString();
            model.CreateDBNewID();
            model.OperateState = IOS.DBUtility.DBOperateType.Insert;
            model.DataType = Convert.ToInt32(SettingParameterCategories.ImplementationParameters);
            model.UserID = -2;
            model.Value = JsonConvert.SerializeObject(list);
            return model;
        }

二、将Json反序列化成对象Object

 /// 
        /// 创建默认宏观计划柱子的颜色
        /// 
        private List CreateDefaultColorOfMacroPlanChartInfo()
        {
            if (m_ColorOfMacroPlanChartInfoList.Count == 0)
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new JavaScriptDateTimeConverter());//指定转化日期的格式
                serializer.NullValueHandling = NullValueHandling.Ignore;//忽略空值

                string fileName = Path.Combine(TGlobal.StartupPath, @"Resources\ColorOfMacroPlanChartInfo.txt");
                using (StreamReader reader = new StreamReader(fileName, Encoding.GetEncoding("gb2312"), true))
                {
                    using (JsonReader jsonReader = new JsonTextReader(reader))
                    {
                        m_ColorOfMacroPlanChartInfoList = serializer.Deserialize>(jsonReader);
                    }
                }
                //SetColor(m_ColorOfMacroPlanChartInfoList);
                //SaveImplementationParameters(m_ColorOfMacroPlanChartInfoList);
            }
            return m_ColorOfMacroPlanChartInfoList;
        }
/// 
        /// 得到指定负载类别的一组颜色
        /// 
        /// 
        /// 
        public List GetLoadingStyles(MacroLoadingStyle loadingStyle)
        {
            //用户参数优先于实施参数
            List resultList = new List();
            ModelSettings modelSetting = GetModelSettings(loadingStyle.ToString());
            if (modelSetting != null)
            {
                resultList = JsonConvert.DeserializeObject>(modelSetting.Value);
            }
            else
            {
                resultList = CreateDefaultColorOfMacroPlanChartInfo();
            }
            SetTitleLanguage(resultList);
            return resultList;
        }

反序列 化字典数据

 if (string.IsNullOrEmpty(textJson)==false)
            {
                Dictionary keyValues = JsonConvert.DeserializeObject>(textJson);
                foreach(var item in items)
                {
                    if(keyValues.ContainsKey(item.Name))
                    {
                        item.Title = keyValues[item.Name].ToString();
                    }
                }
            }

 

你可能感兴趣的:(C#软件开发)