Json.net 常用使用小结

前端之家收集整理的这篇文章主要介绍了Json.net 常用使用小结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

3.5版本dll下载:http://pan.baidu.com/s/1c0vgNWc

  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. namespace microstore
  6. {
  7. public interface IPerson
  8. {
  9. string FirstName
  10. {
  11. get;
  12. set;
  13. }
  14. string LastName
  15. {
  16. get;
  17. set;
  18. }
  19. DateTime BirthDate
  20. {
  21. get;
  22. set;
  23. }
  24. }
  25. public class Employee : IPerson
  26. {
  27. public string FirstName
  28. {
  29. get;
  30. set;
  31. }
  32. public string LastName
  33. {
  34. get;
  35. set;
  36. }
  37. public DateTime BirthDate
  38. {
  39. get;
  40. set;
  41. }
  42.  
  43. public string Department
  44. {
  45. get;
  46. set;
  47. }
  48. public string JobTitle
  49. {
  50. get;
  51. set;
  52. }
  53. }
  54. public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>
  55. {
  56. //重写abstract class CustomCreationConverter<T>的Create方法
  57. public override IPerson Create(Type objectType)
  58. {
  59. return new Employee();
  60. }
  61. }
  62.  
  63. public partial class testjson : System.Web.UI.Page
  64. {
  65. protected void Page_Load(object sender,EventArgs e)
  66. {
  67. //if (!IsPostBack)
  68. // TestJson();
  69. }
  70.  
  71. #region 序列化
  72. public string TestJsonSerialize()
  73. {
  74. Product product = new Product();
  75. product.Name = "Apple";
  76. product.Expiry = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
  77. product.Price = 3.99M;
  78. //product.Sizes = new string[] { "Small","Medium","Large" };
  79.  
  80. //string json = Newtonsoft.Json.JsonConvert.SerializeObject(product); //没有缩进输出
  81. string json = Newtonsoft.Json.JsonConvert.SerializeObject(product,Newtonsoft.Json.Formatting.Indented);
  82. //string json = Newtonsoft.Json.JsonConvert.SerializeObject(
  83. // product,// Newtonsoft.Json.Formatting.Indented,// new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }
  84. //);
  85. return string.Format("<p>{0}</p>",json);
  86. }
  87. public string TestListJsonSerialize()
  88. {
  89. Product product = new Product();
  90. product.Name = "Apple";
  91. product.Expiry = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
  92. product.Price = 3.99M;
  93. product.Sizes = new string[] { "Small","Large" };
  94.  
  95. List<Product> plist = new List<Product>();
  96. plist.Add(product);
  97. plist.Add(product);
  98. string json = Newtonsoft.Json.JsonConvert.SerializeObject(plist,Newtonsoft.Json.Formatting.Indented);
  99. return string.Format("<p>{0}</p>",json);
  100. }
  101. #endregion
  102.  
  103. #region 反序列化
  104. public string TestJsonDeserialize()
  105. {
  106. string strjson = "{\"Name\":\"Apple\",\"Expiry\":\"2014-05-03 10:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}";
  107. Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson);
  108.  
  109. string template = @"<p><ul>
  110. <li>{0}</li>
  111. <li>{1}</li>
  112. <li>{2}</li>
  113. <li>{3}</li>
  114. </ul></p>";
  115.  
  116. return string.Format(template,p.Name,p.Expiry,p.Price.ToString(),string.Join(",",p.Sizes));
  117. }
  118. public string TestListJsonDeserialize()
  119. {
  120. string strjson = "{\"Name\":\"Apple\",\"Large\"]}";
  121. List<Product> plist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]",strjson,strjson));
  122.  
  123. string template = @"<p><ul>
  124. <li>{0}</li>
  125. <li>{1}</li>
  126. <li>{2}</li>
  127. <li>{3}</li>
  128. </ul></p>";
  129.  
  130. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  131. plist.ForEach(x =>
  132. strb.AppendLine(
  133. string.Format(template,x.Name,x.Expiry,x.Price.ToString(),x.Sizes))
  134. )
  135. );
  136. return strb.ToString();
  137. }
  138. #endregion
  139.  
  140. #region 自定义反序列化
  141. public string TestListCustomDeserialize()
  142. {
  143. string strJson = "[ { \"FirstName\": \"Maurice\",\"LastName\": \"Moss\",\"BirthDate\": \"1981-03-08T00:00Z\",\"Department\": \"IT\",\"JobTitle\": \"Support\" },{ \"FirstName\": \"Jen\",\"LastName\": \"Barber\",\"BirthDate\": \"1985-12-10T00:00Z\",\"JobTitle\": \"Manager\" } ] ";
  144. List<IPerson> people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson,new PersonConverter());
  145. IPerson person = people[0];
  146.  
  147. string template = @"<p><ul>
  148. <li>当前List<IPerson>[x]对象类型:{0}</li>
  149. <li>FirstName:{1}</li>
  150. <li>LastName:{2}</li>
  151. <li>BirthDate:{3}</li>
  152. <li>Department:{4}</li>
  153. <li>JobTitle:{5}</li>
  154. </ul></p>";
  155.  
  156. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  157. people.ForEach(x =>
  158. strb.AppendLine(
  159. string.Format(
  160. template,person.GetType().ToString(),x.FirstName,x.LastName,x.BirthDate.ToString(),((Employee)x).Department,((Employee)x).JobTitle
  161. )
  162. )
  163. );
  164. return strb.ToString();
  165. }
  166. #endregion
  167.  
  168. #region 反序列化成Dictionary
  169.  
  170. public string TestDeserialize2Dic()
  171. {
  172. //string json = @"{""key1"":""zhangsan"",""key2"":""lisi""}";
  173. //string json = "{\"key1\":\"zhangsan\",\"key2\":\"lisi\"}";
  174. string json = "{key1:\"zhangsan\",key2:\"lisi\"}";
  175. Dictionary<string,string> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(json);
  176.  
  177. string template = @"<li>key:{0},value:{1}</li>";
  178. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  179. strb.Append("Dictionary<string,string>长度" + dic.Count.ToString() + "<ul>");
  180. dic.AsQueryable().ToList().ForEach(x =>
  181. {
  182. strb.AppendLine(string.Format(template,x.Key,x.Value));
  183. });
  184. strb.Append("</ul>");
  185. return strb.ToString();
  186. }
  187.  
  188. #endregion
  189.  
  190. #region NullValueHandling特性
  191. public class Movie
  192. {
  193. public string Name { get; set; }
  194. public string Description { get; set; }
  195. public string Classification { get; set; }
  196. public string Studio { get; set; }
  197. public DateTime? ReleaseDate { get; set; }
  198. public List<string> ReleaseCountries { get; set; }
  199. }
  200. /// <summary>
  201. /// 完整序列化输出
  202. /// </summary>
  203. public string CommonSerialize()
  204. {
  205. Movie movie = new Movie();
  206. movie.Name = "Bad Boys III";
  207. movie.Description = "It's no Bad Boys";
  208.  
  209. string included = Newtonsoft.Json.JsonConvert.SerializeObject(
  210. movie,Newtonsoft.Json.Formatting.Indented,//缩进
  211. new Newtonsoft.Json.JsonSerializerSettings { }
  212. );
  213.  
  214. return included;
  215. }
  216. /// <summary>
  217. /// 忽略空(Null)对象输出
  218. /// </summary>
  219. /// <returns></returns>
  220. public string IgnoredSerialize()
  221. {
  222. Movie movie = new Movie();
  223. movie.Name = "Bad Boys III";
  224. movie.Description = "It's no Bad Boys";
  225.  
  226. string included = Newtonsoft.Json.JsonConvert.SerializeObject(
  227. movie,//缩进
  228. new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }
  229. );
  230.  
  231. return included;
  232. }
  233. #endregion
  234.  
  235. public class Product
  236. {
  237. public string Name { get; set; }
  238. public string Expiry { get; set; }
  239. public Decimal Price { get; set; }
  240. public string[] Sizes { get; set; }
  241. }
  242.  
  243. #region DefaultValueHandling默认值
  244. public class Invoice
  245. {
  246. public string Company { get; set; }
  247. public decimal Amount { get; set; }
  248.  
  249. // false is default value of bool
  250. public bool Paid { get; set; }
  251. // null is default value of nullable
  252. public DateTime? PaidDate { get; set; }
  253.  
  254. // customize default values
  255. [System.ComponentModel.DefaultValue(30)]
  256. public int FollowUpDays { get; set; }
  257.  
  258. [System.ComponentModel.DefaultValue("")]
  259. public string FollowUpEmailAddress { get; set; }
  260. }
  261. public void GG()
  262. {
  263. Invoice invoice = new Invoice
  264. {
  265. Company = "Acme Ltd.",Amount = 50.0m,Paid = false,FollowUpDays = 30,FollowUpEmailAddress = string.Empty,PaidDate = null
  266. };
  267.  
  268. string included = Newtonsoft.Json.JsonConvert.SerializeObject(
  269. invoice,new Newtonsoft.Json.JsonSerializerSettings { }
  270. );
  271. // {
  272. // "Company": "Acme Ltd.",// "Amount": 50.0,// "Paid": false,// "PaidDate": null,// "FollowUpDays": 30,// "FollowUpEmailAddress": ""
  273. // }
  274.  
  275. string ignored = Newtonsoft.Json.JsonConvert.SerializeObject(
  276. invoice,new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }
  277. );
  278. // {
  279. // "Company": "Acme Ltd.",// "Amount": 50.0
  280. // }
  281. }
  282. #endregion
  283.  
  284. #region JsonIgnoreAttribute and DataMemberAttribute 特性
  285.  
  286. public string OutIncluded()
  287. {
  288. Car car = new Car
  289. {
  290. Model = "zhangsan",Year = DateTime.Now,Features = new List<string> { "aaaa","bbbb","cccc" },LastModified = DateTime.Now.AddDays(5)
  291. };
  292. return Newtonsoft.Json.JsonConvert.SerializeObject(car,Newtonsoft.Json.Formatting.Indented);
  293. }
  294. public string OutIncluded2()
  295. {
  296. Computer com = new Computer
  297. {
  298. Name = "zhangsan",SalePrice = 3999m,Manufacture = "red",StockCount = 5,WholeSalePrice = 34m,NextShipmentDate = DateTime.Now.AddDays(5)
  299. };
  300. return Newtonsoft.Json.JsonConvert.SerializeObject(com,Newtonsoft.Json.Formatting.Indented);
  301. }
  302.  
  303. public class Car
  304. {
  305. // included in JSON
  306. public string Model { get; set; }
  307. public DateTime Year { get; set; }
  308. public List<string> Features { get; set; }
  309.  
  310. // ignored
  311. [Newtonsoft.Json.JsonIgnore]
  312. public DateTime LastModified { get; set; }
  313. }
  314.  
  315. //在nt3.5中需要添加System.Runtime.Serialization.dll引用
  316. [System.Runtime.Serialization.DataContract]
  317. public class Computer
  318. {
  319. // included in JSON
  320. [System.Runtime.Serialization.DataMember]
  321. public string Name { get; set; }
  322. [System.Runtime.Serialization.DataMember]
  323. public decimal SalePrice { get; set; }
  324.  
  325. // ignored
  326. public string Manufacture { get; set; }
  327. public int StockCount { get; set; }
  328. public decimal WholeSalePrice { get; set; }
  329. public DateTime NextShipmentDate { get; set; }
  330. }
  331.  
  332. #endregion
  333.  
  334. #region IContractResolver特性
  335. public class Book
  336. {
  337. public string BookName { get; set; }
  338. public decimal BookPrice { get; set; }
  339. public string AuthorName { get; set; }
  340. public int AuthorAge { get; set; }
  341. public string AuthorCountry { get; set; }
  342. }
  343. public void KK()
  344. {
  345. Book book = new Book
  346. {
  347. BookName = "The Gathering Storm",BookPrice = 16.19m,AuthorName = "Brandon Sanderson",AuthorAge = 34,AuthorCountry = "United States of America"
  348. };
  349. string startingWithA = Newtonsoft.Json.JsonConvert.SerializeObject(
  350. book,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') }
  351. );
  352. // {
  353. // "AuthorName": "Brandon Sanderson",// "AuthorAge": 34,// "AuthorCountry": "United States of America"
  354. // }
  355.  
  356. string startingWithB = Newtonsoft.Json.JsonConvert.SerializeObject(
  357. book,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') }
  358. );
  359. // {
  360. // "BookName": "The Gathering Storm",// "BookPrice": 16.19
  361. // }
  362. }
  363. public class DynamicContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
  364. {
  365. private readonly char _startingWithChar;
  366.  
  367. public DynamicContractResolver(char startingWithChar)
  368. {
  369. _startingWithChar = startingWithChar;
  370. }
  371.  
  372. protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(Type type,Newtonsoft.Json.MemberSerialization memberSerialization)
  373. {
  374. IList<Newtonsoft.Json.Serialization.JsonProperty> properties = base.CreateProperties(type,memberSerialization);
  375.  
  376. // only serializer properties that start with the specified character
  377. properties =
  378. properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
  379.  
  380. return properties;
  381. }
  382. }
  383.  
  384. #endregion
  385.  
  386. //...
  387. }
  388. }
  1. #region Serializing Partial JSON Fragment Example
  2. public class SearchResult
  3. {
  4. public string Title { get; set; }
  5. public string Content { get; set; }
  6. public string Url { get; set; }
  7. }
  8.  
  9. public string SerializingJsonFragment()
  10. {
  11. #region
  12. string googleSearchText = @"{
  13. 'responseData': {
  14. 'results': [{
  15. 'GsearchResultClass': 'GwebSearch','unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton','url': 'http://en.wikipedia.org/wiki/Paris_Hilton','visibleUrl': 'en.wikipedia.org','cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org','title': '<b>Paris Hilton</b> - Wikipedia,the free encyclopedia','titleNoFormatting': 'Paris Hilton - Wikipedia,'content': '[1] In 2006,she released her debut album...'
  16. },{
  17. 'GsearchResultClass': 'GwebSearch','unescapedUrl': 'http://www.imdb.com/name/nm0385296/','url': 'http://www.imdb.com/name/nm0385296/','visibleUrl': 'www.imdb.com','cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com','title': '<b>Paris Hilton</b>','titleNoFormatting': 'Paris Hilton','content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
  18. }],'cursor': {
  19. 'pages': [{
  20. 'start': '0','label': 1
  21. },{
  22. 'start': '4','label': 2
  23. },{
  24. 'start': '8','label': 3
  25. },{
  26. 'start': '12','label': 4
  27. }],'estimatedResultCount': '59600000','currentPageIndex': 0,'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
  28. }
  29. },'responseDetails': null,'responseStatus': 200
  30. }";
  31. #endregion
  32.  
  33. Newtonsoft.Json.Linq.JObject googleSearch = Newtonsoft.Json.Linq.JObject.Parse(googleSearchText);
  34. // get JSON result objects into a list
  35. List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList();
  36. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  37. string template = @"<ul>
  38. <li>Title:{0}</li>
  39. <li>Content: {1}</li>
  40. <li>Url:{2}</li>
  41. </ul>";
  42. listJToken.ForEach(x =>
  43. {
  44. // serialize JSON results into .NET objects
  45. SearchResult searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString());
  46. strb.AppendLine(string.Format(template,searchResult.Title,searchResult.Content,searchResult.Url));
  47. });
  48. return strb.ToString();
  49. }
  50.  
  51. #endregion
  52.  
  53. #region ShouldSerialize
  54. public class CC
  55. {
  56. public string Name { get; set; }
  57. public CC Manager { get; set; }
  58.  
  59. //http://msdn.microsoft.com/en-us/library/53b8022e.aspx
  60. public bool ShouldSerializeManager()
  61. {
  62. // don't serialize the Manager property if an employee is their own manager
  63. return (Manager != this);
  64. }
  65. }
  66. public string ShouldSerializeTest()
  67. {
  68. //create Employee mike
  69. CC mike = new CC();
  70. mike.Name = "Mike Manager";
  71.  
  72. //create Employee joe
  73. CC joe = new CC();
  74. joe.Name = "Joe Employee";
  75. joe.Manager = mike; //set joe'Manager = mike
  76.  
  77. // mike is his own manager
  78. // ShouldSerialize will skip this property
  79. mike.Manager = mike;
  80. return Newtonsoft.Json.JsonConvert.SerializeObject(new[] { joe,mike },Newtonsoft.Json.Formatting.Indented);
  81. }
  82. #endregion
  83.  
  84. //驼峰结构输出(小写打头,后面单词大写)
  85. public string JJJ()
  86. {
  87. Product product = new Product
  88. {
  89. Name = "Widget",Expiry = DateTime.Now.ToString(),Price = 9.99m,Sizes = new[] { "Small","Large" }
  90. };
  91.  
  92. string json = Newtonsoft.Json.JsonConvert.SerializeObject(
  93. product,new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }
  94. );
  95. return json;
  96.  
  97. //{
  98. // "name": "Widget",// "expiryDate": "2010-12-20T18:01Z",// "price": 9.99,// "sizes": [
  99. // "Small",// "Medium",// "Large"
  100. // ]
  101. //}
  102. }
  103.  
  104. #region ITraceWriter
  105. public class Staff
  106. {
  107. public string Name { get; set; }
  108. public List<string> Roles { get; set; }
  109. public DateTime StartDate { get; set; }
  110. }
  111. public void KKKK()
  112. {
  113. Staff staff = new Staff();
  114. staff.Name = "Arnie Admin";
  115. staff.Roles = new List<string> { "Administrator" };
  116. staff.StartDate = new DateTime(2000,12,DateTimeKind.Utc);
  117.  
  118. Newtonsoft.Json.Serialization.ITraceWriter traceWriter = new Newtonsoft.Json.Serialization.MemoryTraceWriter();
  119. Newtonsoft.Json.JsonConvert.SerializeObject(
  120. staff,new Newtonsoft.Json.JsonSerializerSettings
  121. {
  122. TraceWriter = traceWriter,Converters = { new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter() }
  123. }
  124. );
  125.  
  126. Console.WriteLine(traceWriter);
  127. // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
  128. // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
  129. // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
  130. // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
  131. // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
  132. // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
  133. // 2013-05-18T21:38:11.255 Verbose Serialized JSON:
  134. // {
  135. // "Name": "Arnie Admin",// "StartDate": new Date(
  136. // 976623132000
  137. // ),// "Roles": [
  138. // "Administrator"
  139. // ]
  140. // }
  141. }
  142. #endregion
  143.  
  144. public string TestReadJsonFromFile()
  145. {
  146. Linq2Json l2j = new Linq2Json();
  147. Newtonsoft.Json.Linq.JObject jarray = l2j.GetJObject4();
  148. return jarray.ToString();
  149. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace microstore
  7. {
  8. public class Linq2Json
  9. {
  10. #region GetJObject
  11.  
  12. //Parsing a JSON Object from text
  13. public Newtonsoft.Json.Linq.JObject GetJObject()
  14. {
  15. string json = @"{
  16. cpu: 'Intel',Drives: [
  17. 'DVD read/writer','500 gigabyte hard drive'
  18. ]
  19. }";
  20. Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
  21. return jobject;
  22. }
  23.  
  24. /*
  25. * //example:=>
  26. *
  27. Linq2Json l2j = new Linq2Json();
  28. Newtonsoft.Json.Linq.JObject jobject = l2j.GetJObject2(Server.MapPath("json/Person.json"));
  29. //return Newtonsoft.Json.JsonConvert.SerializeObject(jobject,Newtonsoft.Json.Formatting.Indented);
  30. return jobject.ToString();
  31. */
  32. //Loading JSON from a file
  33. public Newtonsoft.Json.Linq.JObject GetJObject2(string jsonPath)
  34. {
  35. using (System.IO.StreamReader reader = System.IO.File.OpenText(jsonPath))
  36. {
  37. Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(reader));
  38. return jobject;
  39. }
  40. }
  41.  
  42. //Creating JObject
  43. public Newtonsoft.Json.Linq.JObject GetJObject3()
  44. {
  45. List<Post> posts = GetPosts();
  46. Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.FromObject(new
  47. {
  48. channel = new
  49. {
  50. title = "James Newton-King",link = "http://james.newtonking.com",description = "James Newton-King's blog.",item =
  51. from p in posts
  52. orderby p.Title
  53. select new
  54. {
  55. title = p.Title,description = p.Description,link = p.Link,category = p.Category
  56. }
  57. }
  58. });
  59.  
  60. return jobject;
  61. }
  62. /*
  63. {
  64. "channel": {
  65. "title": "James Newton-King","link": "http://james.newtonking.com","description": "James Newton-King's blog.","item": [{
  66. "title": "jewron","description": "4546fds","link": "http://www.baidu.com","category": "jhgj"
  67. },{
  68. "title": "jofdsn","description": "mdsfan","category": "6546"
  69. },{
  70. "title": "jokjn","description": "m3214an","category": "hg425"
  71. },{
  72. "title": "jon","description": "man","category": "goodman"
  73. }]
  74. }
  75. }
  76. */
  77. //Creating JObject
  78. public Newtonsoft.Json.Linq.JObject GetJObject4()
  79. {
  80. List<Post> posts = GetPosts();
  81. Newtonsoft.Json.Linq.JObject RSS = new Newtonsoft.Json.Linq.JObject(
  82. new Newtonsoft.Json.Linq.JProperty("channel",new Newtonsoft.Json.Linq.JObject(
  83. new Newtonsoft.Json.Linq.JProperty("title","James Newton-King"),new Newtonsoft.Json.Linq.JProperty("link","http://james.newtonking.com"),new Newtonsoft.Json.Linq.JProperty("description","James Newton-King's blog."),new Newtonsoft.Json.Linq.JProperty("item",new Newtonsoft.Json.Linq.JArray(
  84. from p in posts
  85. orderby p.Title
  86. select new Newtonsoft.Json.Linq.JObject(
  87. new Newtonsoft.Json.Linq.JProperty("title",p.Title),p.Description),p.Link),new Newtonsoft.Json.Linq.JProperty("category",new Newtonsoft.Json.Linq.JArray(
  88. from c in p.Category
  89. select new Newtonsoft.Json.Linq.JValue(c)
  90. )
  91. )
  92. )
  93. )
  94. )
  95. )
  96. )
  97. );
  98.  
  99. return RSS;
  100. }
  101. /*
  102. {
  103. "channel": {
  104. "title": "James Newton-King","category": ["j","h","g","j"]
  105. },"category": ["6","5","4","6"]
  106. },"category": ["h","2","5"]
  107. },"category": ["g","o","d","m","a","n"]
  108. }]
  109. }
  110. }
  111. */
  112.  
  113. public class Post
  114. {
  115. public string Title { get; set; }
  116. public string Description { get; set; }
  117. public string Link { get; set; }
  118. public string Category { get; set; }
  119. }
  120. private List<Post> GetPosts()
  121. {
  122. List<Post> listp = new List<Post>()
  123. {
  124. new Post{Title="jon",Description="man",Link="http://www.baidu.com",Category="goodman"},new Post{Title="jofdsn",Description="mdsfan",Category="6546"},new Post{Title="jewron",Description="4546fds",Category="jhgj"},new Post{Title="jokjn",Description="m3214an",Category="hg425"}
  125. };
  126. return listp;
  127. }
  128.  
  129. #endregion
  130.  
  131. #region GetJArray
  132. /*
  133. * //example:=>
  134. *
  135. Linq2Json l2j = new Linq2Json();
  136. Newtonsoft.Json.Linq.JArray jarray = l2j.GetJArray();
  137. return Newtonsoft.Json.JsonConvert.SerializeObject(jarray,Newtonsoft.Json.Formatting.Indented);
  138. //return jarray.ToString();
  139. */
  140. //Parsing a JSON Array from text
  141. public Newtonsoft.Json.Linq.JArray GetJArray()
  142. {
  143. string json = @"[
  144. 'Small','Medium','Large'
  145. ]";
  146.  
  147. Newtonsoft.Json.Linq.JArray jarray = Newtonsoft.Json.Linq.JArray.Parse(json);
  148. return jarray;
  149. }
  150.  
  151. //Creating JArray
  152. public Newtonsoft.Json.Linq.JArray GetJArray2()
  153. {
  154. Newtonsoft.Json.Linq.JArray array = new Newtonsoft.Json.Linq.JArray();
  155. Newtonsoft.Json.Linq.JValue text = new Newtonsoft.Json.Linq.JValue("Manual text");
  156. Newtonsoft.Json.Linq.JValue date = new Newtonsoft.Json.Linq.JValue(new DateTime(2000,5,23));
  157. //add to JArray
  158. array.Add(text);
  159. array.Add(date);
  160.  
  161. return array;
  162. }
  163.  
  164. #endregion
  165.  
  166. //待续...
  167.  
  168. }
  169. }


测试效果

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testjson.aspx.cs" Inherits="microstore.testjson" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml" >
  6. <head runat="server">
  7. <title></title>
  8. <style type="text/css">
  9. body{ font-family:Arial,微软雅黑; font-size:14px;}
  10. a{ text-decoration:none; color:#333;}
  11. a:hover{ text-decoration:none; color:#f00;}
  12. </style>
  13. </head>
  14. <body>
  15. <form id="form1" runat="server">
  16. <h3>序列化对象</h3>
  17. 表现1:<br />
  18. <%=TestJsonSerialize()%>
  19. <%=TestListJsonSerialize() %>
  20. 表现2:<br />
  21. <%=TestListJsonSerialize2() %>
  22. <hr />
  23. <h3>反序列化对象</h3>
  24. <p>单个对象</p>
  25. <%=TestJsonDeserialize() %>
  26. <p>多个对象</p>
  27. <%=TestListJsonDeserialize() %>
  28. <p>反序列化成数据字典Dictionary</p>
  29. <%=TestDeserialize2Dic() %>
  30. <hr />
  31. <h3>自定义反序列化</h3>
  32. <%=TestListCustomDeserialize()%>
  33. <hr />
  34. <h3>序列化输出的忽略特性</h3>
  35. NullValueHandling特性忽略=><br />
  36. <%=CommonSerialize() %><br />
  37. <%=IgnoredSerialize()%><br /><br />
  38. 属性标记忽略=><br />
  39. <%=OutIncluded() %><br />
  40. <%=OutIncluded2() %>
  41. <hr />
  42. <h3>Serializing Partial JSON Fragments</h3>
  43. <%=SerializingJsonFragment() %>
  44. <hr />
  45. <h3>ShouldSerialize</h3>
  46. <%=ShouldSerializeTest() %><br />
  47. <%=JJJ() %><br /><br />
  48. <%=TestReadJsonFromFile() %>
  49. </form>
  50. </body>
  51. </html>
显示

序列化对象

表现1:

{ "Name": "Apple","Expiry": "2014-05-04 02:08:58","Price": 3.99,"Sizes": null }

[ { "Name": "Apple","Sizes": [ "Small","Large" ] },{ "Name": "Apple","Large" ] } ]

表现2:

[ { "Name": "Apple","Large" ] } ]


反序列化对象

单个对象

  • Apple
  • 2014-05-03 10:20:59
  • 3.99
  • Small,Medium,Large

多个对象

  • Apple
  • 2014-05-03 10:20:59
  • 3.99
  • Small,Large
  • Apple
  • 2014-05-03 10:20:59
  • 3.99
  • Small,Large

反序列化成数据字典Dictionary

Dictionary长度2
  • key:key1,value:zhangsan
  • key:key2,value:lisi

自定义反序列化

  • 当前List[x]对象类型:microstore.Employee
  • FirstName:Maurice
  • LastName:Moss
  • BirthDate:1981-3-8 0:00:00
  • Department:IT
  • JobTitle:Support
  • 当前List[x]对象类型:microstore.Employee
  • FirstName:Jen
  • LastName:Barber
  • BirthDate:1985-12-10 0:00:00
  • Department:IT
  • JobTitle:Manager

序列化输出的忽略特性

NullValueHandling特性忽略=>
{ "Name": "Bad Boys III","Description": "It's no Bad Boys","Classification": null,"Studio": null,"ReleaseDate": null,"ReleaseCountries": null }
{ "Name": "Bad Boys III","Description": "It's no Bad Boys" }

属性标记忽略=>
{ "Model": "zhangsan","Year": "2014-05-01T02:08:58.671875+08:00","Features": [ "aaaa","cccc" ] }
{ "Name": "zhangsan","SalePrice": 3999.0 }

Serializing Partial JSON Fragments

  • Title:Paris Hilton - Wikipedia,the free encyclopedia
  • Content: [1] In 2006,she released her debut album...
  • Url:http://en.wikipedia.org/wiki/Paris_Hilton
  • Title:Paris Hilton
  • Content: Self: Zoolander. Socialite Paris Hilton...
  • Url:http://www.imdb.com/name/nm0385296/

ShouldSerialize

[ { "Name": "Joe Employee","Manager": { "Name": "Mike Manager" } },{ "Name": "Mike Manager" } ] { "name": "Widget","expiry": "2014-5-1 2:08:58","price": 9.99,"sizes": [ "Small","Large" ] } { "channel": { "title": "James Newton-King","item": [ { "title": "jewron","category": [ "j","j" ] },{ "title": "jofdsn","category": [ "6","6" ] },{ "title": "jokjn","category": [ "h","5" ] },{ "title": "jon","category": [ "g","n" ] } ] } }

猜你在找的Json相关文章