JSON extension class -- JsonHelper, json extension jsonhelper
1. Reference The Newtonsoft. Json Library (JSON. NET ).
2. copy and paste JsonHelper.
Using System; using System. collections. generic; using System. linq; using Newtonsoft. json; using Newtonsoft. json. converters; namespace Allen. core {public static partial class JsonHelper {# region Private fields private static readonly JsonSerializerSettings JsonSettings; private const string EmptyJson = "[]"; # endregion # region Constructor static JsonHelper () {var datetimeConverter = new IsoDateTimeConv Erter {DateTimeFormat = "yyyy-MM-dd HH: mm: ss"}; JsonSettings = new JsonSerializerSettings {MissingMemberHandling = MissingMemberHandling. ignore, NullValueHandling = NullValueHandling. ignore, ReferenceLoopHandling = ReferenceLoopHandling. ignore}; JsonSettings. converters. add (datetimeConverter);} # endregion # region Public Methods // <summary> // apply Formatting. none and the specified JsonSerializerSettings. Convert an object to a JSON string // </summary> /// <param name = "obj"> Any object </param> /// <param name =" jsonSettings "> In A Newtonsoft. json. specifies the setting on the JsonSerializer object. If it is null, use the default settings </param> /// <returns> standard JSON string </returns> public static string ToJson (object obj, JsonSerializerSettings jsonSettings) {return ToJson (obj, Formatting. none, jsonSettings);} // <summary> // The Formatting enumerated value specified by the application is None and the specified JsonSerializerSettings Settings, serialize an object to a JSON string // </summary> /// <param name = "obj"> Any object </param> /// <param name =" format "> specify Newtonsoft. json. jsonTextWriter format setting options </param> /// <param name = "jsonSettings"> In A Newtonsoft. json. specifies the setting on the JsonSerializer object. If it is null, use the default settings </param> /// <returns> standard JSON format string </returns> public static string ToJson (object obj, Formatting format, JsonSerializerSettings jsonSettings) {try {return obj = Null? EmptyJson: JsonConvert. SerializeObject (obj, format, jsonSettings ?? JsonSettings);} catch (Exception) {// todo log return EmptyJson; }}/// <summary> // deserialize JSON data to the specified. NET Type object // <para> If a JsonSerializationException occurs, retry the operation as a set and retrieve the first T object of the set. </Para> // <para> the conversion fails or another exception occurs, returns the default value of the T object </para> /// </summary> /// <param name = "json"> JSON string to be deserialized </param> // /<param name = "jsonSettings"> In A Newtonsoft. json. specifies the setting on the JsonSerializer object. If it is null, use the default settings </param> /// <typeparam name = "T"> deserialization object type </typeparam> /// <returns> </returns> public static T FromJson <T> (string json, jsonSerializerSettings jsonSettings) where T: class, new () {return FromJson <T> (j Son, Formatting. none, jsonSettings);} // <summary> // deserialize JSON data to the specified. NET Type object // <para> If a JsonSerializationException occurs, retry the operation as a set and retrieve the first T object of the set. </Para> // <para> the conversion fails or another exception occurs, returns the default value of the T object </para> /// </summary> /// <param name = "json"> JSON string to be deserialized </param> // /<param name = "format"> specify Newtonsoft. json. jsonTextWriter format setting options </param> /// <param name = "jsonSettings"> In A Newtonsoft. json. specifies the setting on the JsonSerializer object. If it is null, use the default settings </param> /// <typeparam name = "T"> deserialization object type </typeparam> /// <returns> </returns> public static T FromJson <T> (string json, formatt Ing format, JsonSerializerSettings jsonSettings) where T: class, new () {T result; if (jsonSettings = null) {jsonSettings = JsonSettings;} try {result = string. isNullOrWhiteSpace (json )? Default (T): JsonConvert. deserializeObject <T> (json, jsonSettings);} catch (JsonSerializationException) // retry in the form of a set after this exception occurs. {// LOG try {var array = JsonConvert. deserializeObject <IEnumerable <T> (json, jsonSettings); result = array. firstOrDefault () ;}catch (Exception) {// LOG result = default (T) ;}} catch (Exception) {// LOG result = default (T );} return result;} # endregion # region Public Ex Tend Methods /// <summary> /// deserialize JSON data to the specified. NET Type object // <para> If a JsonSerializationException occurs, retry the operation as a set and retrieve the first T object of the set. </Para> // <para> the conversion fails or another exception occurs, returns the default value of the T object </para> /// </summary> /// <param name = "json"> JSON string to be deserialized </param> // /<typeparam name = "T"> deserialization object type </typeparam> // <returns> </returns> public static T FromJson <T> (this string json) where T: class, new () {return FromJson <T> (json, Formatting. none, JsonSettings);} /// <summary> // set the Default Formatting enumerated values of the application None and the default JsonSerializerSettings. serialize the object to a string in JSON format. /// </Summary> /// <param name = "obj"> Any object </param> /// <returns> standard JSON string </returns> public static string toJson (this object obj) {return ToJson (obj, Formatting. none, JsonSettings);} public static string ToJson <TSource> (this IEnumerable <TSource> source, Func <TSource, bool> predicate, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (predicate), isFilterNull) ;} Public static string ToJson <TSource> (this IEnumerable <TSource> source, Func <TSource, int, bool> predicate, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (predicate), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, TResult> selector, bool isFilterNull = true) {return DelegateToJson (source, Enumerable => enumerable. Where (t => t! = Null ). select (selector), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, int, TResult> selector, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (t => t! = Null ). select (selector), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, bool> predicate, Func <TSource, TResult> selector, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (predicate ). select (selector), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, bool> predicate, Func <TSource, int, TResult> selector, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (predicate ). select (selector), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, int, bool> predicate, Func <TSource, TResult> selector, bool isFilterNull = true) {return DelegateToJ Son (source, enumerable => enumerable. where (predicate ). select (selector), isFilterNull);} public static string ToJson <TSource, TResult> (this IEnumerable <TSource> source, Func <TSource, int, bool> predicate, Func <TSource, int, TResult> selector, bool isFilterNull = true) {return DelegateToJson (source, enumerable => enumerable. where (predicate ). select (selector), isFilterNull);} # endregion # region Pri Vate Methods /// <summary> /// delegate processing to serialize an object in JSON format and return a string in standard JSON format. /// Null objects are filtered by default. If you need to filter the null objects by yourself when calling the upper-layer interface, // set isFilterNull to false. It is not recommended that isFilterNull be set to false. /// </Summary> /// <typeparam name = "TSource"> </typeparam> /// <typeparam name = "TResult"> </typeparam> /// <param name = "source"> object to be converted to a JSON string </param> /// <param name = "func"> delegate the set/array conditional filtering method, returns the filtered set/array </param> /// <param name = "isFilterNull"> whether to filter null objects in IEnumerable <TSource> source, the default value is true </param> /// <returns> A string in the standard JSON format </returns> private static string DelegateToJson <TSource, TResult> (IEnumerable <TSource> source, Func <TSource [], IEnumerable <TResult> func, bool isFilterNull = true) {return DelegateToJson (source, enumerable => func (enumerable ). toJson (), isFilterNull);} // <summary> // the object to be serialized into JSON format by Delegate processing, and a standard JSON string is returned. /// Null objects are filtered by default. If you need to filter the null objects by yourself when calling the upper-layer interface, // set isFilterNull to false. It is not recommended that isFilterNull be set to false. /// </Summary> /// <typeparam name = "TSource"> </typeparam> /// <param name = "source"> the string to be converted to JSON format object </param> /// <param name = "func"> delegate the JSON processing method, returns a JSON string </param> // <param name = "isFilterNull"> whether to filter null objects in IEnumerable <TSource> source, the default value is true </param> /// <returns> A string in the standard JSON format </returns> private static string DelegateToJson <TSource> (IEnumerable <TSource> source, func <TSource [], string> func, bool is FilterNull = true) {if (source = null) {return EmptyJson;} TSource [] enumerable; if (isFilterNull) {// filter null enumerable = source. where (t => t! = Null). ToArray ();} else {// do not filter null. However, when there is a null object in the upper layer, the Where or Select operation may cause an exception. Enumerable = source as TSource []? Source. ToArray ();} return enumerable. Any ()? Func (enumerable): EmptyJson;} # endregion }}
Usage case:
Class Program {static void Main (string [] args) {// ToJson method Test # region filters null objects by default var list1 = new List <Test> {new Test {Id = 10, type = 21, Name = "Allen"}, new Test {Id = 11, Type = 22}, new Test {Id = 12, Type = 23 }, new Test {Id = 13, Type = 24, Name = "Peter"}, null, new Test {Id = 13, Type = 24, Name = null }}; // specify the json data attribute string jsonString = list1.ToJson (t => new {id = t. id, type = t. type}); // recommended syntax, even true is omitted // string jsonString = JsonHelper. toJson (list1, t => new {id = t. id, type = t. type}); // This statement is not recommended. // string jsonString = list1.ToJson (t => new {id = t. id, type = t. type}, true); Console. writeLine (jsonString); // filter out the jsonString2 = list1.ToJson (t => t. name = "Allen"); // recommended statement, even true is omitted // string jsonString2 = JsonHelper. toJson (list1, t => t. name = "Allen"); // This statement is not recommended. // string jsonString2 = list1.ToJson (t => t. name = "Allen", true); Console. writeLine (jsonString2); // filter out the object named "Allen" and specify the attribute string jsonString3 = list1.ToJson (t => t. name = "Allen", t => new {id = t. id, type = t. type}); // recommended syntax, even true is omitted // string jsonString3 = JsonHelper. toJson (list1, t => t. name = "Allen", t => new {id = t. id, type = t. type}); // This statement is not recommended. // string jsonString3 = list1.ToJson (t => t. name = "Allen", t => new {id = t. id, type = t. type}, true); Console. writeLine (jsonString3); # endregion # region does not filter null objects var list2 = new List <Test> {new Test {Id = 10, Type = 21, Name = "Allen "}, new Test {Id = 11, Type = 22, Name = "Bolong"}, new Test {Id = 12, Type = 23, Name = "Popo "}, new Test {Id = 13, Type = 24, Name = "Peter"}, new Test {Id = 16, Type = 25, Name = "Willy "}}; // specify the json data attribute string jsonString4 = list2.ToJson (t => new {id = t. id, type = t. type}, false); Console. writeLine (jsonString4); // filter out the object string jsonString5 = list2.ToJson (t => t. name = "Allen", false); Console. writeLine (jsonString5); // filter out the object named "Allen" and specify the attribute string jsonString6 = list2.ToJson (t => t. name = "Allen", t => new {id = t. id, type = t. type}, false); Console. writeLine (jsonString6); # endregion // FromJson <T> method Test List <Test> testList1 = jsonString. fromJson <List <Test> (); List <Test> testList2 = jsonString2.FromJson <List <Test> (); Test test = jsonString3.FromJson <Test> (); Console. readKey () ;}} internal class Test {public int Type {get; set ;}public int Id {get; set ;}public string Name {get; set ;}}
PS: Are there any suggestions for better encapsulation?