json.net灵活的实现.net对象和json之间进行转换,且性能比其他两种json序列化性能更高,使用方便简单。json.net使用的好处有如下几种:
- 序列化和反序列化JSON(JsonConvert)
string output = JsonConvert.SerializeObject(product) //序列化//反序列化Product deserializedProduct = JsonConvert.DeserializeObject(output)
-
JsonSerializer的使用
JsonSerializer可以直接通过流的方式来操作JSON数据。将对象转化为JSON格式的字符串,然后存储到本地:
Product product = new Product();product.ExpiryDate = new DateTime(2008, 12, 28);JsonSerializer serializer = new JsonSerializer();serializer.Converters.Add(new JavaScriptDateTimeConverter());//指定转化日期的格式serializer.NullValueHandling = NullValueHandling.Ignore;//忽略空值using (StreamWriter sw = new StreamWriter(@"d:\json.txt"))using (JsonWriter writer = new JsonTextWriter(sw)){ serializer.Serialize(writer, product); // {"ExpiryDate":new Date(1230375600000),"Price":0}}
将本地文件中的Json格式数据,转化为JObject对象:
JsonSerializer serializer = new JsonSerializer();serializer.Converters.Add(new JavaScriptDateTimeConverter());//指定转化日期的格式serializer.NullValueHandling = NullValueHandling.Ignore;//忽略空值using (StreamReader sr = new StreamReader(@"d:\json.txt"))using (JsonReader reader= new JsonTextReader(sr)){ JObject jo =(JObject) serializer.Deserialize(reader);// {// "Name": null,// "ExpiryDate": "2008-12-28T00:00:00",// "Price": 0.0,// "Sizes": null//}}
案例中的 serializer.NullValueHandling = NullValueHandling.Ignore 表示忽略空值,也就是为null值的属性不转化,需要注意Decimal的默认值不是null,而是0。
-
LINQ to JSON
Linq to Json可以非常快速的从JObject对象中查询数据,以及创建JObject对象。
// create JObjectJObject o = JObject.Parse(@"{ 'CPU': 'Intel', 'Drives': [ 'DVD read/writer', '500 gigabyte hard drive' ] }"); // query JObject string cpu = (string)o["CPU"];// Intelstring firstDrive = (string)o["Drives"][0];// DVD read/writerIListallDrives = o["Drives"].Select(t => (string)t).ToList();// DVD read/writer// 500 gigabyte hard drive
- json和XML之间互相转换
//JSON转换成XMLstring json = @"{ '@Id': 1, 'Email': 'james@example.com', 'Active': true, 'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [ 'User', 'Admin' ], 'Team': { '@Id': 2, 'Name': 'Software Developers', 'Description': 'Creators of fine software products and services.' }}";XNode node = JsonConvert.DeserializeXNode(json, "Root");//// james@example.com //true //2013-01-20T00:00:00Z //User //Admin //// //Software Developers //Creators of fine software products and services. //
//XML转换成JSONstring xml = @"";XmlDocument doc = new XmlDocument();doc.LoadXml(xml);string json = JsonConvert.SerializeXmlNode(doc);Console.WriteLine(json);// {// "?xml": {// "@version": "1.0",// "@standalone": "no"// },// "root": {// "person": [// {// "@id": "1",// "name": "Alan",// "url": "http://www.google.com"// },// {// "@id": "2",// "name": "Louis",// "url": "http://www.yahoo.com"// }// ]// }// } Alan http://www.google.com Louis http://www.yahoo.com