版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u011127019/article/details/51706619

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
使用方法简单:
使用命令

  1. Install-Package Newtonsoft.Json

或者右键,项目》Nuget包管理,添加

简答使用实例如下:

1.定义类:

  1. /// <summary>
  2. /// 学生信息实体
  3. /// </summary>
  4. public class Student
  5. {
  6. public int ID { get; set; }
  7. public string Name { get; set; }
  8. public Class Class { get; set; }
  9. }
  10. /// <summary>
  11. /// 学生班级实体
  12. /// </summary>
  13. public class Class
  14. {
  15. public int ID { get; set; }
  16. public string Name { get; set; }
  17. }

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

  1. Student stu = new Student();
  2. stu.ID = 1;
  3. stu.Name = "张三";
  4. stu.Class = new Class() { ID = 0121, Name = "CS0121" };
  5. //使用方法1
  6. //实体序列化、反序列化
  7. //结果:{"ID":1,"Name":"张三","Class":{"ID":121,"Name":"CS0121"}}
  8. string json1 = JsonConvert.SerializeObject(stu);
  9. Console.WriteLine(json1);
  10. Student stu2 = JsonConvert.DeserializeObject<Student>(json1);
  11. Console.WriteLine(stu2.Name + "---" + stu2.Class.Name);
  12. //实体集合,序列化和反序列化
  13. List<Student> stuList = new List<Student>() { stu, stu2 };
  14. string json2 = JsonConvert.SerializeObject(stuList);
  15. Console.WriteLine(json2);
  16. List<Student> stuList2 = JsonConvert.DeserializeObject<List<Student>>(json2);
  17. foreach (var item in stuList2)
  18. {
  19. Console.WriteLine(item.Name + "----" + item.Class.Name);
  20. }
  21. //匿名对象的解析,
  22. //匿名独享的类型 obj.GetType().Name: "<>f__AnonymousType0`2"
  23. var obj = new { ID = 2, Name = "李四" };
  24. string json3 = JsonConvert.SerializeObject(obj);
  25. Console.WriteLine(json3);
  26. object obj2 = JsonConvert.DeserializeAnonymousType(json3, obj);
  27. Console.WriteLine(obj2.GetType().GetProperty("ID").GetValue(obj2));
  28. object obj3 = JsonConvert.DeserializeAnonymousType(json3, new { ID = default(int), Name = default(string) });
  29. Console.WriteLine(obj3.GetType().GetProperty("ID").GetValue(obj3));
  30. //匿名对象解析,可以传入现有类型,进行转换
  31. Student stu3 = new Student();
  32. stu3 = JsonConvert.DeserializeAnonymousType(json3, new Student());
  33. Console.WriteLine(stu3.Name);

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

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

更多常用实例:
Linq To JSON 一
LINQ to JSON 实例二
其他参考博客:http://www.cnblogs.com/freshman0216/p/4161800.html