JSON.NET框架實現C#對象和JSON字符串的轉換


什么是JSON.NET

JSON.NET是一款高性能的JSON轉換工具,和其他JSON序列化工具相比性能絕對出色。它由James Newton-Kind開發,你也可以前往他的個人項目主頁中獲取更多關於JSON.NET的信息:http://james.newtonking.com/json

json的了解,參考: http://blog.csdn.net/ful1021/article/details/38516787

序列化 JSON(List數據同樣適用)

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
 
string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Sizes": [
//    "Small"
//  ]
//}

反序列化 JSON

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

List數據處理:

//反序列化JSON字符串,將JSON字符串轉換成LIST列表  
List<Customer> _list = JsonConvert.DeserializeObject<List<Customer>>(jsonText);    

LINQ to JSON

JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));

JObject o = new JObject();
o["MyArray"] = array;

string json = o.ToString();
// {
//   "MyArray": [
//     "Manual text",
//     "2000-05-23T00:00:00"
//   ]
// }

Validate JSON

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'name': 'James',
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
// true

版權聲明:本文為博主原創文章,未經博主允許不得轉載。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM