(1)将本地文件中的数据反序列化成实体对象
(2)将实体对象序列化
.txt中json格式的数据为:{"Name":"张三","Age":20,"Address":"上海市徐汇区"}
第一步:
添加dll引用:Newtonsoft.Json.dll (网上下载一个)
using Newtonsoft.Json;
第二步:
新建一个Student实体类:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Main方法:
static void Main(string[] args)
{
string str = "";
using (StreamReader sw = new StreamReader(@"D:\student.txt", Encoding.Default))
{
str = sw.ReadToEnd();
}
if (!String.IsNullOrEmpty(str))
{
//反序列化(将{"Name":"张三","Age":20,"Address":"上海市徐汇区"}转化成实体)
Student st = JsonConvert.DeserializeObject<Student>(str);
Console.WriteLine("反序列化:" + "Name:" + st.Name + ", Age:" + st.Age.ToString() + ", Address:" + st.Address);
//序列化(将实体对象st转化成:{"Name":"张三","Age":20,"Address":"上海市徐汇区"})
string strSerialize = JsonConvert.SerializeObject(st);
Console.WriteLine("序列化: " + strSerialize);
}
Console.Read();
}
运行结果如下: