C#保存数据,JSON格式(winform窗体)

我那天作数据保存,想用JSON格式方便记事本打开查看。

当然也可以使用string字符串,或者bin,xml格式的文件保存

JSON格式的文件用记事本格式如下:

[
  {
    "Name": "Language",
    "Index": 3
  },
  {
    "Name": "Volume",
    "Index": 15
  }
]

这里就保存了两个数字,下面演示实现过程:

1.序列化和反序列化:

安装Newtonsoft.Json包:

序列化和 反序列化代码:

    public class JsonStore
    {
        private string storePath;
        public string StorePath
        {
            get { return storePath; }
            set { storePath = value; }
        }

        public bool StoreJosn(object data)
        {
            bool res = true;
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
            try
            {
                File.WriteAllText(storePath, json, Encoding.UTF8);
            }
            catch(Exception ex)
            { 
                Console.WriteLine(ex.Message);
                res = false;

            }
            return res;
        }

        public List<T> ReadJson<T>()
        {
            if(File.Exists(storePath))
            {
                string jsonStr = File.ReadAllText(storePath);
                List<StoreData> deserializedPeople = JsonConvert.DeserializeObject<List<StoreData>>(jsonStr);
                var list = new List<T>(JsonConvert.DeserializeObject<List<T>>(jsonStr));
                return list;       
            }
            return null;
        }
    }
    [Serializable]
    public class StoreData
    {
        public string Name { get; set;}
        public int Index { get; set; }
    }

 调用样例:

//存
JsonStore json = new JsonStore();
List<StoreData> stores = new List<StoreData>();
stores.Add(new StoreData { Name = "Language", Index = comboBox_Lung.SelectedIndex });
stores.Add(new StoreData { Name = "Volume", Index = comboBox_volume.SelectedIndex });
            json.StorePath = jsonPath;
            json.StoreJosn(stores);
//读取json
jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Datafile");
if(!Directory.Exists(jsonPath))
{
    Directory.CreateDirectory(jsonPath);
}
JsonStore json = new JsonStore();
jsonPath = Path.Combine(jsonPath, "jsondata.txt");
json.StorePath = jsonPath;
List<StoreData> datas;
datas = json.ReadJson<StoreData>();

还带存储的哦!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值