当前位置:   article > 正文

C# 解析JSON方法总结_formatting.indented

formatting.indented

主要参考http://blog.csdn.net/joyhen/article/details/24805899和http://www.cnblogs.com/yanweidie/p/4605212.html

根据自己需求,做些测试、修改、整理。

使用Newtonsoft.Json

一、用JsonConvert序列化和反序列化。

实体类不用特殊处理,正常定义属性即可,控制属性是否被序列化参照高级用法1。

  1. public interface IPerson
  2. {
  3. string FirstName
  4. {
  5. get;
  6. set;
  7. }
  8. string LastName
  9. {
  10. get;
  11. set;
  12. }
  13. DateTime BirthDate
  14. {
  15. get;
  16. set;
  17. }
  18. }
  19. public class Employee : IPerson
  20. {
  21. public string FirstName
  22. {
  23. get;
  24. set;
  25. }
  26. public string LastName
  27. {
  28. get;
  29. set;
  30. }
  31. public DateTime BirthDate
  32. {
  33. get;
  34. set;
  35. }
  36. public string Department
  37. {
  38. get;
  39. set;
  40. }
  41. public string JobTitle
  42. {
  43. get;
  44. set;
  45. }
  46. public string NotSerialize { get; set; }
  47. }
  48. public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>
  49. {
  50. //重写abstract class CustomCreationConverter<T>的Create方法
  51. public override IPerson Create(Type objectType)
  52. {
  53. return new Employee();
  54. }
  55. }
  56. public class Product
  57. {
  58. public string Name { get; set; }
  59. public DateTime Expiry { get; set; }
  60. public Decimal Price { get; set; }
  61. public string[] Sizes { get; set; }
  62. public string NotSerialize { get; set; }
  63. }

1.序列化代码:

  1. #region 序列化 用JsonConvert
  2. public string TestJsonSerialize()
  3. {
  4. Product product = new Product();
  5. product.Name = "Apple";
  6. product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
  7. product.Price = 3.99M;
  8. //string json = Newtonsoft.Json.JsonConvert.SerializeObject(product); //没有缩进输出
  9. string json = Newtonsoft.Json.JsonConvert.SerializeObject(product, Newtonsoft.Json.Formatting.Indented);//有缩进输出
  10. //string json = Newtonsoft.Json.JsonConvert.SerializeObject(
  11. // product,
  12. // Newtonsoft.Json.Formatting.Indented,
  13. // new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }//参照高级用法中有关JsonSerializerSettings用法
  14. //);
  15. return json;
  16. }
  17. public string TestListJsonSerialize()
  18. {
  19. Product product = new Product();
  20. product.Name = "Apple";
  21. product.Expiry = DateTime.Now;//.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
  22. product.Price = 3.99M;
  23. product.Sizes = new string[] { "Small", "Medium", "Large" };
  24. List<Product> plist = new List<Product>();
  25. plist.Add(product);
  26. plist.Add(product);
  27. string json = Newtonsoft.Json.JsonConvert.SerializeObject(plist, Newtonsoft.Json.Formatting.Indented);
  28. return json;
  29. }
  30. #endregion
2.反序列化代码:

  1. #region 反序列化 用JsonConvert
  2. public string TestJsonDeserialize()
  3. {
  4. string strjson = "{\"Name\":\"Apple\",\"Expiry\":\"2014-05-03 10:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}";
  5. Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson);
  6. string template = @"
  7. Name:{0}
  8. Expiry:{1}
  9. Price:{2}
  10. Sizes:{3}
  11. ";
  12. return string.Format(template, p.Name, p.Expiry, p.Price.ToString(), string.Join(",", p.Sizes));
  13. }
  14. public string TestListJsonDeserialize()
  15. {
  16. string strjson = "{\"Name\":\"Apple\",\"Expiry\":\"2014-05-03 10:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}";
  17. List<Product> plist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]", strjson, strjson));
  18. string template = @"
  19. Name:{0}
  20. Expiry:{1}
  21. Price:{2}
  22. Sizes:{3}
  23. ";
  24. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  25. plist.ForEach(x =>
  26. strb.AppendLine(
  27. string.Format(template, x.Name, x.Expiry, x.Price.ToString(), string.Join(",", x.Sizes))
  28. )
  29. );
  30. return strb.ToString();
  31. }
  32. #endregion
3.自定义序列化,使用实体类中定义的PersonConverter,每反序列化一次实体时会调用一次PersonConverter,还没想清楚如何用。

  1. #region 自定义反序列化
  2. public string TestListCustomDeserialize()
  3. {
  4. string strJson = "[ { \"FirstName\": \"Maurice\", \"LastName\": \"Moss\", \"BirthDate\": \"1981-03-08T00:00Z\", \"Department\": \"IT\", \"JobTitle\": \"Support\" }, { \"FirstName\": \"Jen\", \"LastName\": \"Barber\", \"BirthDate\": \"1985-12-10T00:00Z\", \"Department\": \"IT\", \"JobTitle\": \"Manager\" } ] ";
  5. List<IPerson> people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson, new PersonConverter());
  6. IPerson person = people[0];
  7. string template = @"
  8. 当前List<IPerson>[x]对象类型:{0}
  9. FirstName:{1}
  10. LastName:{2}
  11. BirthDate:{3}
  12. Department:{4}
  13. JobTitle:{5}
  14. ";
  15. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  16. people.ForEach(x =>
  17. strb.AppendLine(
  18. string.Format(
  19. template,
  20. person.GetType().ToString(),
  21. x.FirstName,
  22. x.LastName,
  23. x.BirthDate.ToString(),
  24. ((Employee)x).Department,
  25. ((Employee)x).JobTitle
  26. )
  27. )
  28. );
  29. return strb.ToString();
  30. }
  31. #endregion

4、获取Json字符串中部分内容

  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. public string SerializingJsonFragment()
  9. {
  10. #region
  11. string googleSearchText = @"{
  12. 'responseData': {
  13. 'results': [{
  14. 'GsearchResultClass': 'GwebSearch',
  15. 'unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton',
  16. 'url': 'http://en.wikipedia.org/wiki/Paris_Hilton',
  17. 'visibleUrl': 'en.wikipedia.org',
  18. 'cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org',
  19. 'title': '<b>Paris Hilton</b> - Wikipedia, the free encyclopedia',
  20. 'titleNoFormatting': 'Paris Hilton - Wikipedia, the free encyclopedia',
  21. 'content': '[1] In 2006, she released her debut album...'
  22. },
  23. {
  24. 'GsearchResultClass': 'GwebSearch',
  25. 'unescapedUrl': 'http://www.imdb.com/name/nm0385296/',
  26. 'url': 'http://www.imdb.com/name/nm0385296/',
  27. 'visibleUrl': 'www.imdb.com',
  28. 'cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com',
  29. 'title': '<b>Paris Hilton</b>',
  30. 'titleNoFormatting': 'Paris Hilton',
  31. 'content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
  32. }],
  33. 'cursor': {
  34. 'pages': [{
  35. 'start': '0',
  36. 'label': 1
  37. },
  38. {
  39. 'start': '4',
  40. 'label': 2
  41. },
  42. {
  43. 'start': '8',
  44. 'label': 3
  45. },
  46. {
  47. 'start': '12',
  48. 'label': 4
  49. }],
  50. 'estimatedResultCount': '59600000',
  51. 'currentPageIndex': 0,
  52. 'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
  53. }
  54. },
  55. 'responseDetails': null,
  56. 'responseStatus': 200
  57. }";
  58. #endregion
  59. Newtonsoft.Json.Linq.JObject googleSearch = Newtonsoft.Json.Linq.JObject.Parse(googleSearchText);
  60. // get JSON result objects into a list
  61. List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList();
  62. System.Text.StringBuilder strb = new System.Text.StringBuilder();
  63. string template = @"
  64. Title:{0}
  65. Content: {1}
  66. Url:{2}
  67. ";
  68. listJToken.ForEach(x =>
  69. {
  70. // serialize JSON results into .NET objects
  71. SearchResult searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString());
  72. strb.AppendLine(string.Format(template, searchResult.Title, searchResult.Content, searchResult.Url));
  73. });
  74. return strb.ToString();
  75. }
  76. #endregion
输出结果

  1. Title:<b>Paris Hilton</b> - Wikipedia, the free encyclopedia
  2. Content: [1] In 2006, she released her debut album...
  3. Url:http://en.wikipedia.org/wiki/Paris_Hilton
  4. Title:<b>Paris Hilton</b>
  5. Content: Self: Zoolander. Socialite <b>Paris Hilton</b>...
  6. Url:http://www.imdb.com/name/nm0385296/
5、利用Json.Linq序列化

可以突破实体类的限制,自由组合要序列化的值

  1. public class Linq2Json
  2. {
  3. #region GetJObject
  4. //Parsing a JSON Object from text
  5. public Newtonsoft.Json.Linq.JObject GetJObject()
  6. {
  7. string json = @"{
  8. CPU: 'Intel',
  9. Drives: [
  10. 'DVD read/writer',
  11. '500 gigabyte hard drive'
  12. ]
  13. }";
  14. Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
  15. return jobject;
  16. }
  17. /*
  18. * //example:=>
  19. *
  20. Linq2Json l2j = new Linq2Json();
  21. Newtonsoft.Json.Linq.JObject jobject = l2j.GetJObject2(Server.MapPath("json/Person.json"));
  22. //return Newtonsoft.Json.JsonConvert.SerializeObject(jobject, Newtonsoft.Json.Formatting.Indented);
  23. return jobject.ToString();
  24. */
  25. //Loading JSON from a file
  26. public Newtonsoft.Json.Linq.JObject GetJObject2(string jsonPath)
  27. {
  28. using (System.IO.StreamReader reader = System.IO.File.OpenText(jsonPath))
  29. {
  30. Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(reader));
  31. return jobject;
  32. }
  33. }
  34. //Creating JObject
  35. public Newtonsoft.Json.Linq.JObject GetJObject3()
  36. {
  37. List<Post> posts = GetPosts();
  38. Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.FromObject(new
  39. {
  40. channel = new
  41. {
  42. title = "James Newton-King",
  43. link = "http://james.newtonking.com",
  44. description = "James Newton-King's blog.",
  45. item =
  46. from p in posts
  47. orderby p.Title
  48. select new
  49. {
  50. title = p.Title,
  51. description = p.Description,
  52. link = p.Link,
  53. category = p.Category
  54. }
  55. }
  56. });
  57. return jobject;
  58. }
  59. /*
  60. {
  61. "channel": {
  62. "title": "James Newton-King",
  63. "link": "http://james.newtonking.com",
  64. "description": "James Newton-King's blog.",
  65. "item": [{
  66. "title": "jewron",
  67. "description": "4546fds",
  68. "link": "http://www.baidu.com",
  69. "category": "jhgj"
  70. },
  71. {
  72. "title": "jofdsn",
  73. "description": "mdsfan",
  74. "link": "http://www.baidu.com",
  75. "category": "6546"
  76. },
  77. {
  78. "title": "jokjn",
  79. "description": "m3214an",
  80. "link": "http://www.baidu.com",
  81. "category": "hg425"
  82. },
  83. {
  84. "title": "jon",
  85. "description": "man",
  86. "link": "http://www.baidu.com",
  87. "category": "goodman"
  88. }]
  89. }
  90. }
  91. */
  92. //Creating JObject
  93. public Newtonsoft.Json.Linq.JObject GetJObject4()
  94. {
  95. List<Post> posts = GetPosts();
  96. Newtonsoft.Json.Linq.JObject rss = new Newtonsoft.Json.Linq.JObject(
  97. new Newtonsoft.Json.Linq.JProperty("channel",
  98. new Newtonsoft.Json.Linq.JObject(
  99. new Newtonsoft.Json.Linq.JProperty("title", "James Newton-King"),
  100. new Newtonsoft.Json.Linq.JProperty("link", "http://james.newtonking.com"),
  101. new Newtonsoft.Json.Linq.JProperty("description", "James Newton-King's blog."),
  102. new Newtonsoft.Json.Linq.JProperty("item",
  103. new Newtonsoft.Json.Linq.JArray(
  104. from p in posts
  105. orderby p.Title
  106. select new Newtonsoft.Json.Linq.JObject(
  107. new Newtonsoft.Json.Linq.JProperty("title", p.Title),
  108. new Newtonsoft.Json.Linq.JProperty("description", p.Description),
  109. new Newtonsoft.Json.Linq.JProperty("link", p.Link),
  110. new Newtonsoft.Json.Linq.JProperty("category",
  111. new Newtonsoft.Json.Linq.JArray(
  112. from c in p.Category
  113. select new Newtonsoft.Json.Linq.JValue(c)
  114. )
  115. )
  116. )
  117. )
  118. )
  119. )
  120. )
  121. );
  122. return rss;
  123. }
  124. /*
  125. {
  126. "channel": {
  127. "title": "James Newton-King",
  128. "link": "http://james.newtonking.com",
  129. "description": "James Newton-King's blog.",
  130. "item": [{
  131. "title": "jewron",
  132. "description": "4546fds",
  133. "link": "http://www.baidu.com",
  134. "category": ["j", "h", "g", "j"]
  135. },
  136. {
  137. "title": "jofdsn",
  138. "description": "mdsfan",
  139. "link": "http://www.baidu.com",
  140. "category": ["6", "5", "4", "6"]
  141. },
  142. {
  143. "title": "jokjn",
  144. "description": "m3214an",
  145. "link": "http://www.baidu.com",
  146. "category": ["h", "g", "4", "2", "5"]
  147. },
  148. {
  149. "title": "jon",
  150. "description": "man",
  151. "link": "http://www.baidu.com",
  152. "category": ["g", "o", "o", "d", "m", "a", "n"]
  153. }]
  154. }
  155. }
  156. */
  157. public class Post
  158. {
  159. public string Title { get; set; }
  160. public string Description { get; set; }
  161. public string Link { get; set; }
  162. public string Category { get; set; }
  163. }
  164. private List<Post> GetPosts()
  165. {
  166. List<Post> listp = new List<Post>()
  167. {
  168. new Post{Title="jon",Description="man",Link="http://www.baidu.com",Category="goodman"},
  169. new Post{Title="jofdsn",Description="mdsfan",Link="http://www.baidu.com",Category="6546"},
  170. new Post{Title="jewron",Description="4546fds",Link="http://www.baidu.com",Category="jhgj"},
  171. new Post{Title="jokjn",Description="m3214an",Link="http://www.baidu.com",Category="hg425"}
  172. };
  173. return listp;
  174. }
  175. #endregion
  176. #region GetJArray
  177. /*
  178. * //example:=>
  179. *
  180. Linq2Json l2j = new Linq2Json();
  181. Newtonsoft.Json.Linq.JArray jarray = l2j.GetJArray();
  182. return Newtonsoft.Json.JsonConvert.SerializeObject(jarray, Newtonsoft.Json.Formatting.Indented);
  183. //return jarray.ToString();
  184. */
  185. //Parsing a JSON Array from text
  186. public Newtonsoft.Json.Linq.JArray GetJArray()
  187. {
  188. string json = @"[
  189. 'Small',
  190. 'Medium',
  191. 'Large'
  192. ]";
  193. Newtonsoft.Json.Linq.JArray jarray = Newtonsoft.Json.Linq.JArray.Parse(json);
  194. return jarray;
  195. }
  196. //Creating JArray
  197. public Newtonsoft.Json.Linq.JArray GetJArray2()
  198. {
  199. Newtonsoft.Json.Linq.JArray array = new Newtonsoft.Json.Linq.JArray();
  200. Newtonsoft.Json.Linq.JValue text = new Newtonsoft.Json.Linq.JValue("Manual text");
  201. Newtonsoft.Json.Linq.JValue date = new Newtonsoft.Json.Linq.JValue(new DateTime(2000, 5, 23));
  202. //add to JArray
  203. array.Add(text);
  204. array.Add(date);
  205. return array;
  206. }
  207. #endregion
  208. }

使用方式

  1. Linq2Json l2j = new Linq2Json();
  2. Newtonsoft.Json.Linq.JObject jarray = l2j.GetJObject4();
  3. return jarray.ToString();


二、高级用法

1.忽略某些属性

当实体类中定义了很多属性,但序列化时只想针对某些属性时可以采用此方式。这种需求还可以细分为运行时不同时刻参与序列化属性集合不固定和固定两种情况。

1)能解决参与序列化属性集合固定的情况

OptOut     默认值,类中所有公有成员会被序列化,如果不想被序列化,可以用特性JsonIgnore
OptIn     默认情况下,所有的成员不会被序列化,类中的成员只有标有特性JsonProperty的才会被序列化,当类的成员很多,但客户端仅仅需要一部分数据时,很有用

仅需要姓名属性:

  1. [JsonObject(MemberSerialization.OptIn)]
  2. public class Person
  3. {
  4. public int Age { get; set; }
  5. [JsonProperty]
  6. public string Name { get; set; }
  7. public string Sex { get; set; }
  8. public bool IsMarry { get; set; }
  9. public DateTime Birthday { get; set; }
  10. }
输出结果


不需要是否结婚属性

  1. [JsonObject(MemberSerialization.OptOut)]
  2. public class Person
  3. {
  4. public int Age { get; set; }
  5. public string Name { get; set; }
  6. public string Sex { get; set; }
  7. [JsonIgnore]
  8. public bool IsMarry { get; set; }
  9. public DateTime Birthday { get; set; }
  10. }
输出结果


通过上面的例子可以看到,要实现不返回某些属性的需求很简单。1.在实体类上加上[JsonObject(MemberSerialization.OptOut)] 2.在不需要返回的属性上加上 [JsonIgnore]说明。

2)能解决参与序列化属性集合不固定的情况

方法1:通过设置忽略默认值属性方式。有点傻。

方法2:继承默认的DefaultContractResolver类,传入需要输出的属性。



2、默认值

可以设置某个属性的默认值,然后序列化或反序列化时自动判断是否默认值,然后选择是否忽略对具有默认值的属性序列化或反序列化。

序列化时想忽略默认值属性可以通过JsonSerializerSettings.DefaultValueHandling来确定,该值为枚举值。

DefaultValueHandling.Ignore     序列化和反序列化时,忽略默认值
DefaultValueHandling.Include    序列化和反序列化时,包含默认值

  1. [DefaultValue(10)]
  2. public int Age { get; set; }
  1. Person p = new Person { Age = 10, Name = "张三丰", Sex = "男", IsMarry = false, Birthday = new DateTime(1991, 1, 2) };
  2. JsonSerializerSettings jsetting=new JsonSerializerSettings();
  3. jsetting.DefaultValueHandling=DefaultValueHandling.Ignore;
  4. Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));
输出结果


3、空值

与默认值类似,可以选择是否忽略对空值的属性序列化或反序列化。

序列化时需要忽略值为NULL的属性,可以通过JsonSerializerSettings.NullValueHandling来确定,另外通过JsonSerializerSettings设置属性是对序列化过程中所有属性生效的,想单独对某一个属性生效可以使用JsonProperty,下面将分别展示两个方式。

1)JsonSerializerSettings.NullValueHandling方式,会忽略实体中全部空值参数

  1. Person p = new Person { room=null,Age = 10, Name = "张三丰", Sex = "男", IsMarry = false, Birthday = new DateTime(1991, 1, 2) };
  2. JsonSerializerSettings jsetting=new JsonSerializerSettings();
  3. jsetting.NullValueHandling = NullValueHandling.Ignore;
  4. Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));

上例中不会序列化room。

2)JsonProperty,忽略特定的属性

  1. [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
  2. public Room room { get; set; }

4、支持非公共属性

  1. [JsonProperty]
  2. private int Height { get; set; }

5、日期

对于Dateime类型日期的格式化就比较麻烦了,系统自带的会格式化成iso日期标准,但是实际使用过程中大多数使用的可能是yyyy-MM-dd 或者yyyy-MM-dd HH:mm:ss两种格式的日期,解决办法是可以将DateTime类型改成string类型自己格式化好,然后在序列化。如果不想修改代码,可以采用下面方案实现。

      Json.Net提供了IsoDateTimeConverter日期转换这个类,可以通过JsnConverter实现相应的日期转换

  1. [JsonConverter(typeof(IsoDateTimeConverter))]
  2. public DateTime Birthday { get; set; }
但是IsoDateTimeConverter日期格式不是我们想要的,我们可以继承该类实现自己的日期

  1. public class ChinaDateTimeConverter : DateTimeConverterBase
  2. {
  3. private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" };
  4. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  5. {
  6. return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
  7. }
  8. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  9. {
  10. dtConverter.WriteJson(writer, value, serializer);
  11. }
  12. }

自己实现了一个yyyy-MM-dd格式化转换类,可以看到只是初始化IsoDateTimeConverter时给的日期格式为yyyy-MM-dd即可,下面看下效果

  1. [JsonConverter(typeof(ChinaDateTimeConverter))]
  2. public DateTime Birthday { get; set; }

日期处理也可以通过设置全局JsonConvert.DefaultSettings,设置JsonSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"。

6、自定义序列化时的属性名称

等同于DataMember中PropertyName作用。

实体中定义的属性名可能不是自己想要的名称,但是又不能更改实体定义,这个时候可以自定义序列化字段名称。

  1. [JsonProperty(PropertyName = "CName")]
  2. public string Name { get; set; }

7、枚举值的自定义格式化

默认情况下对于实体里面的枚举类型系统是格式化成改枚举对应的整型数值,那如果需要格式化成枚举对应的字符怎么处理呢?

  1. public enum NotifyType
  2. {
  3. /// <summary>
  4. /// Emil发送
  5. /// </summary>
  6. Mail=0,
  7. /// <summary>
  8. /// 短信发送
  9. /// </summary>
  10. SMS=1
  11. }
  12. public class TestEnmu
  13. {
  14. /// <summary>
  15. /// 消息发送类型
  16. /// </summary>
  17. [JsonConverter(typeof(StringEnumConverter))]
  18. public NotifyType Type { get; set; }
  19. }
输出结果


8、自定义类型转换

默认情况下对于实体里面的Boolean系统是格式化成true或者false,对于true转成"是" false转成"否"这种需求改怎么实现了?我们可以自定义类型转换实现该需求,下面看实例

  1. public class BoolConvert : JsonConverter
  2. {
  3. private string[] arrBString { get; set; }
  4. public BoolConvert()
  5. {
  6. arrBString = "是,否".Split(',');
  7. }
  8. /// <summary>
  9. /// 构造函数
  10. /// </summary>
  11. /// <param name="BooleanString">将bool值转换成的字符串值</param>
  12. public BoolConvert(string BooleanString)
  13. {
  14. if (string.IsNullOrEmpty(BooleanString))
  15. {
  16. throw new ArgumentNullException();
  17. }
  18. arrBString = BooleanString.Split(',');
  19. if (arrBString.Length != 2)
  20. {
  21. throw new ArgumentException("BooleanString格式不符合规定");
  22. }
  23. }
  24. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  25. {
  26. bool isNullable = IsNullableType(objectType);
  27. Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
  28. if (reader.TokenType == JsonToken.Null)
  29. {
  30. if (!IsNullableType(objectType))
  31. {
  32. throw new Exception(string.Format("不能转换null value to {0}.", objectType));
  33. }
  34. return null;
  35. }
  36. try
  37. {
  38. if (reader.TokenType == JsonToken.String)
  39. {
  40. string boolText = reader.Value.ToString();
  41. if (boolText.Equals(arrBString[0], StringComparison.OrdinalIgnoreCase))
  42. {
  43. return true;
  44. }
  45. else if (boolText.Equals(arrBString[1], StringComparison.OrdinalIgnoreCase))
  46. {
  47. return false;
  48. }
  49. }
  50. if (reader.TokenType == JsonToken.Integer)
  51. {
  52. //数值
  53. return Convert.ToInt32(reader.Value) == 1;
  54. }
  55. }
  56. catch (Exception ex)
  57. {
  58. throw new Exception(string.Format("Error converting value {0} to type '{1}'", reader.Value, objectType));
  59. }
  60. throw new Exception(string.Format("Unexpected token {0} when parsing enum", reader.TokenType));
  61. }
  62. /// <summary>
  63. /// 判断是否为Bool类型
  64. /// </summary>
  65. /// <param name="objectType">类型</param>
  66. /// <returns>为bool类型则可以进行转换</returns>
  67. public override bool CanConvert(Type objectType)
  68. {
  69. return true;
  70. }
  71. public bool IsNullableType(Type t)
  72. {
  73. if (t == null)
  74. {
  75. throw new ArgumentNullException("t");
  76. }
  77. return (t.BaseType.FullName=="System.ValueType" && t.GetGenericTypeDefinition() == typeof(Nullable<>));
  78. }
  79. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  80. {
  81. if (value == null)
  82. {
  83. writer.WriteNull();
  84. return;
  85. }
  86. bool bValue = (bool)value;
  87. if (bValue)
  88. {
  89. writer.WriteValue(arrBString[0]);
  90. }
  91. else
  92. {
  93. writer.WriteValue(arrBString[1]);
  94. }
  95. }
  96. }

自定义了BoolConvert类型,继承自JsonConverter。构造函数参数BooleanString可以让我们自定义将true false转换成相应字符串。下面看实体里面怎么使用这个自定义转换类型

  1. public class Person
  2. {
  3. [JsonConverter(typeof(BoolConvert))]
  4. public bool IsMarry { get; set; }
  5. }


相应的有什么个性化的转换需求,都可以使用自定义转换类型的方式实现。

9、全局序列化设置

对全局缺省JsonSerializerSettings设置,省却每处都要相同设置代码的麻烦。

  1. Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
  2. JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
  3. {
  4.     //日期类型默认格式化处理
  5.   setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
  6. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  7.     //空值处理
  8. setting.NullValueHandling = NullValueHandling.Ignore;
  9. //高级用法九中的Bool类型转换 设置
  10. setting.Converters.Add(new BoolConvert("是,否"));
  11. return setting;
  12. });




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/861679
推荐阅读
相关标签
  

闽ICP备14008679号