Json序列化和反序列化(Newtonsoft)& 嵌套反序列化
<1> 序列化单个实体对象
(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();
}
运行结果如下:
<2> 嵌套反序列化
例如,需要序列化下面的json数据:
string Content =
{
"rc": 1,
"re": [
{
"id": 123,
"name": "张三",
"age": 20,
}
]
}
需要定义下面两个实体类:
public class UserNameInfo
{
public int rc { get; set; }
public List<UserInfo> re { get; set; } //注意:这里一定要用List<T>
}
public class UserInfo
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
反序列化即可:
var item = JsonUtil<UserNameInfo>.Deserialize(Content); //Content为要反序列化的Json格式的字符串