我那天作数据保存,想用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>();
还带存储的哦!