C# Json序列化工具--Newtonsoft.Json简介和使用

Newtonsoft.Json,是.Net中开源的Json序列化和反序列化工具,官方地址:http://www.newtonsoft.com/json。

功能比较多,效率比较高,官方给出对比数据

50% faster than DataContractJsonSerializer, and 250% faster than JavaScriptSerializer.

比较常用的功能除了序列化发序列化之外,还有 Linq To Json、Json Path、 XML support等

更多详情参考:http://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm

使用方法简单:

使用命令

Install-Package Newtonsoft.Json
或者右键,项目》Nuget包管理,添加

简答使用实例如下:

1.定义类:

/// 
/// 学生信息实体
/// 
public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public Class Class { get; set; }
}
/// 
/// 学生班级实体
/// 
public class Class
{
    public int ID { get; set; }
    public string Name { get; set; }
}

2.序列化,反序列化 实体对象,实体集合,匿名对象:

Student stu = new Student();
stu.ID = 1;
stu.Name = "张三";
stu.Class = new Class() { ID = 0121, Name = "CS0121" };

//使用方法1
//实体序列化、反序列化
//结果:{"ID":1,"Name":"张三","Class":{"ID":121,"Name":"CS0121"}}
string json1 = JsonConvert.SerializeObject(stu);
Console.WriteLine(json1);
Student stu2 = JsonConvert.DeserializeObject(json1);
Console.WriteLine(stu2.Name + "---" + stu2.Class.Name);

//实体集合,序列化和反序列化
List stuList = new List() { stu, stu2 };
string json2 = JsonConvert.SerializeObject(stuList);
Console.WriteLine(json2);
List stuList2 = JsonConvert.DeserializeObject>(json2);
foreach (var item in stuList2)
{
    Console.WriteLine(item.Name + "----" + item.Class.Name);
}

//匿名对象的解析,
//匿名独享的类型  obj.GetType().Name: "<>f__AnonymousType0`2"
var obj = new { ID = 2, Name = "李四" };
string json3 = JsonConvert.SerializeObject(obj);
Console.WriteLine(json3);
object obj2 = JsonConvert.DeserializeAnonymousType(json3, obj);
Console.WriteLine(obj2.GetType().GetProperty("ID").GetValue(obj2));
object obj3 = JsonConvert.DeserializeAnonymousType(json3, new { ID = default(int), Name = default(string) });
Console.WriteLine(obj3.GetType().GetProperty("ID").GetValue(obj3));
//匿名对象解析,可以传入现有类型,进行转换
Student stu3 = new Student();
stu3 = JsonConvert.DeserializeAnonymousType(json3, new Student());
Console.WriteLine(stu3.Name);


2.控制字符串的序列化,更方便:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.DateFormatString = "yyyy-MM-dd";
string str = JsonConvert.SerializeObject(_Context.students.First(), settings);
Console.WriteLine(str);
{"sno":"101","sname":"李军","ssex":"男","sbirthday":"1976-02-20","_class":"95033"}


更多常用实例:

Linq To JSON 一

LINQ to JSON 实例二

其他参考博客:http://www.cnblogs.com/freshman0216/p/4161800.html

你可能感兴趣的:(序列化和反序列化,C#,Newtonsoft.Json)