背景:
在我们退出软件时常常需要记录当前的一个状态,而不是在打开软件是加载默认值,所以需要将当前软件的一些属性值或者对象保存下来,保存方式有多种,之前写过一个通过将对象保存成二进制文件的方法,可以参考: https://www.cnblogs.com/sclu/p/13689755.html
现在要介绍的是通过将数据保存成JSON文件的方式。
一。创建一个要序列化的类Product。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSONTest
{
class Product
{
public string Name;
public DateTime ExpiryDate;
public decimal Price;
public string[] Sizes;
}
}
二。NuGET中添加Newton soft.Json.
三。创建Product类的对象,并赋值。用SerializeObject将对象序列化成string,用DeserializeObject将string反序列化成对象。
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JSONTest
{
class Program
{
static void Main(string[] args)
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
JsonSerializer serializer = new JsonSerializer();
TextReader tr = new StringReader(output);
JsonTextReader jtr = new JsonTextReader(tr);
object obj = serializer.Deserialize(jtr);
if (obj != null)
{
StringWriter textWriter = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar = ' '
};
serializer.Serialize(jsonWriter, obj);
textWriter.ToString();
StreamWriter sw = new StreamWriter(@"c:/test.json", false);//将数据保存本地
sw.Write(textWriter.ToString());
sw.Flush();
sw.Close();
}
StreamReader sr = new StreamReader(@"c: est.json", Encoding.Default);
string input = sr.ReadToEnd();
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(input);
}
}
}
Note:
详细或者更多的例子可以参考官方的Document,其中介绍了读写JSON,序列化反序列化集合对象,字典对象等等。 https://www.newtonsoft.com/json/help/html/Introduction.htm