下载地址:http://www.newtonsoft.com/json
参考官网文档:http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
使用前:请添加引用 NewTonsoft.Json程序集
一、JsonConver用于JSON字符串和对象之间的相互转换
string SerializeObject(object):用于将对象转化成JSON格式的字符串
T DeserializeObject<T>(string):用于将JSON格式的字符串转化成对象
案例:
Product类
1 using System.Collections.Generic; 2 using System.Linq; 3 using System.Text; 4 using System.Threading.Tasks; 5 6 namespace ConsoleApplication1 7 { 8 class Product 9 { 10 public string Name { get; set; } 11 12 public decimal Price; 13 14 public string[] Size { get; set; } 15 } 16 }
使用方式:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using Newtonsoft.Json; 7 using Newtonsoft.Json.Linq; 8 9 namespace ConsoleApplication1 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Product product = new Product() 16 { 17 Name = "Apple", 18 Price = 4.2M, 19 Size = new string[] {"Small","Medium","Large"} 20 }; 21 //将对象转化成JSON字符串 22 string output = JsonConvert.SerializeObject(product); 23 Console.WriteLine(output); 24 //将JSON字符串转化成对象 25 Product product2 = JsonConvert.DeserializeObject<Product>(output); 26 Console.WriteLine(product2); 27 Console.WriteLine(product2.Name); 28 Console.ReadLine(); 29 } 30 } 31 }
输出结果: