JSON extension class--jsonhelper

Source: Internet
Author: User
Tags tojson

1. Refer to the Newtonsoft.json Library (json.net).

2. Copy and paste the Jsonhelper bar.

Source:

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 fie        lds private static readonly jsonserializersettings jsonsettings;        Private Const string Emptyjson = "[]"; #endregion #region Constructor Static jsonhelper () {var datetimeconverter = new Isodateti            meconverter {DateTimeFormat = "yyyy-mm-dd HH:mm:ss"}; Jsonsettings = new Jsonserializersettings {missingmemberhandling = Missingmemberhandling.ignore , nullvaluehandling = nullvaluehandling.ignore, referenceloophandling = Referenceloophandlin            G.ignore};        JSONSETTINGS.CONVERTERS.ADD (Datetimeconverter); } #endregion #region Public Methods//<summary>//Apply Formatting.none and designated jsonserialize Rsettings Settings, serializing objectsString to JSON format///</summary>//<param name= "obj" > any object </param>//<param name= "Jsonsettings" > Specify settings on a Newtonsoft.Json.JsonSerializer object, if NULL, use default settings </param>//<returns> Standard J            Son format string </returns> public static string ToJson (Object obj, Jsonserializersettings jsonsettings) {        return ToJson (obj, Formatting.none, jsonsettings); }///<summary>///Apply the specified formatting enumeration value of None and the specified jsonserializersettings setting, serialize the object to a JSON-formatted string///&LT ;/summary>//<param name= "obj" > any object </param>//<param name= "format" > Specify Newtonsoft. Json.jsontextwriter formatting options </param>///<param Name= "Jsonsettings" > in a Newtonsoft.Json.JsonSerializer pair As specified on the settings, if NULL, the default setting is used </param>///<returns> Standard JSON-formatted string </returns> public static string T        Ojson (object obj, formatting format, jsonserializersettings jsonsettings){try {return obj = = null?} EmptyJson:JsonConvert.SerializeObject (obj, format, jsonsettings??).            Jsonsettings);            } catch (Exception) {//todo LOG return emptyjson;        }}///<summary>///apply Formatting.none and specified jsonserializersettings settings to deserialize JSON data as a dynamic object <para> If an jsonserializationexception exception occurs, retry again as a collection, removing the first dynamic object of the collection. </para>///<para> conversion fails, or other exception occurs, returns the default value of the dynamic object </para>///</summary>//&lt ;p Aram Name= "JSON" > JSON string to Deserialize </param>//<param name= "Jsonsettings" > in a Newtonsoft.Json.JsonSer Specify settings on the Ializer object, and if NULL, use the default settings </param>///<returns>dynamic objects </returns> public static dyn Amic Fromjson (This string json, Jsonserializersettings jsonsettings) {return fromjson<dynamic> (JS On, Formatting.none, jsonsettings);        }///<summary>///Apply the specified formatting enumeration value of None and the specified jsonserializersettings setting to deserialize the JSON data as a dynamic object <para> If an jsonserializationexception exception occurs, retry again as a collection, removing the first dynamic object of the collection. </para>///<para> conversion fails, or other exception occurs, returns the default value of the dynamic object </para>///</summary>//&lt  ;p Aram Name= "JSON" > JSON string to Deserialize </param>//<param name= "format" > Specify Newtonsoft.Json.JsonTextWriter formatting options </param>///<param Name= "jsonsettings" > Specify settings on a Newtonsoft.Json.JsonSerializer object, if NULL, use the default Settings </param>//<returns>dynamic object </returns> public static dynamic Fromjson (This string JS On, formatting format, jsonserializersettings jsonsettings) {return fromjson<dynamic> (JSON, forma        T, jsonsettings); }///<summary>///apply Formatting.none and specified jsonserializersettings settings to deserialize JSON data to the specified. NET type object///&L t;para> if jsonserializationexcept occursIon exception, and then retry again as a collection, removing the first T object of the collection.  </para>///<para> conversion fails, or other exception occurs, returns the default value of the T object </para>///</summary>//<param Name= "JSON" > JSON string to Deserialize </param>//<param name= "Jsonsettings" > in a Newtonsoft.Json.JsonSerialize Specify settings on R object, if NULL, use default settings </param>//<typeparam name= "T" > Deserialization object Type </typeparam>//<re  turns></returns> public static T fromjson<t> (string json, Jsonserializersettings jsonsettings) where        T:class, New () {return fromjson<t> (JSON, Formatting.none, jsonsettings); }///<summary>///Apply the specified formatting enumeration value of None and the specified jsonserializersettings setting to deserialize the JSON data into the specified. NET type object/ <para> If an jsonserializationexception exception occurs, retry again as a collection, removing the first T object of the collection.  </para>///<para> conversion fails, or other exception occurs, returns the default value of the T object </para>///</summary>//<param Name= "JSON" > JSON string to Deserialize </param>//&LT;param name= "Format" > Specify formatting options for Newtonsoft.Json.JsonTextWriter </param>//<param name= "Jsonsettings" & gt; Specify settings on a Newtonsoft.Json.JsonSerializer object, if NULL, use default settings </param>///<typeparam Name= "T" > Deserialization object Type </typeparam>///<returns></returns> public static T fromjson<t> (string json, Format            Ting 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)//After the exception has occurred, retry again in the same way as the collection. {//log try {var array = Jsonconvert.deserializeobject&lt    ;ienumerable<t>> (JSON, jsonsettings);                result = array.                FirstOrDefault ();                } catch (Exception) {//log result = default (T); }} catch (Exception) {//log result = Default (T            );        } return result;        } #endregion #region Public Extend Methods//<summary>///deserialize JSON data as a dynamic object <para> If an jsonserializationexception exception occurs, retry again as a collection, removing the first dynamic object of the collection. </para>///<para> conversion fails, or other exception occurs, returns the default value of the dynamic object </para>///</summary>//&lt ;p Aram Name= "JSON" > JSON string to Deserialize </param>//<returns>dynamic object </returns> public Stati C Dynamic Fromjson (this string json) {return fromjson<dynamic> (JSON, Formatting.none, jsonsetting        s);   }///<summary>//Deserialize JSON data to the specified. NET type Object     <para> If an jsonserializationexception exception occurs, retry again as a collection, removing the first T object of the collection.  </para>///<para> conversion fails, or other exception occurs, returns the default value of the T object </para>///</summary>//<param Name= "JSON" > JSON string to Deserialize </param>//<typeparam name= "T" > type of deserialized object </typeparam>///            lt;returns></returns> public static T fromjson<t> (this string json) where T:class, new () {        Return fromjson<t> (JSON, Formatting.none, jsonsettings); }///<summary>///Apply the default formatting enumeration value of None and the default Jsonserializersettings setting, serialize the object to a JSON-formatted string///&LT ;/summary>//<param name= "obj" > any object </param>//<returns> standard JSON-formatted string </returns&        Gt        public static string ToJson (This object obj) {return ToJson (obj, Formatting.none, jsonsettings); } public static string tojson<tsource> (this ienumerable<tsource> source, func&Lt 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, TRes Ult> selector, bool Isfilternull = True) {return Delegatetojson (source, enumerable = enumerable. Where (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 = = 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 delegatet Ojson (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 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, int, tresult> selector, bool Isfilternull = True) {return Dele Gatetojson (source, enumerable = enumerable. Where (predicate).        Select (selector), isfilternull); } #endregion #region Private Methods///<summary>///delegate processing of objects that need to be serialized into JSON format, returning the standard JSON-formatted word        Character string.        By default, NULL objects are filtered, and if a null object needs to be filtered on its own when the upper layer is called,///set Isfilternull to False, Isfilternull set to False is not recommended. </summary>//<typeparam name= "TSource" ></typeparam>//<typeparam name= "TResult" ></typeparam>//<param name= "source" > objects that need to be converted to JSON format Strings </param>///<param name= "Fu NC "> Collection/Array conditional filter method delegate, return filtered collection/array </param>///<param Name= "Isfilternull" > whether to filter null objects in Ienumerable<tsource> source, default to true</param>//<returns> Standard JSON-formatted string </returns> private static string Delegatetojson<tsource, Tresult> (ienumerable<tsource> Source, func<tsource[], ienumerable<tresult>> Func, bool Isfilternull = True) {return Deleg Atetojson (source, enumerable = func (enumerable).        ToJson (), isfilternull);        }///<summary>///delegate processing of objects that need to be serialized in JSON format, return a standard JSON-formatted string.        By default, NULL objects are filtered, and if a null object needs to be filtered on its own when the upper layer is called,///set Isfilternull to False, Isfilternull set to False is not recommended. </summary>//<typeparam name= "TSource" ></typeparam>//<param name= "source" > Required object to convert to JSON-formatted string </param>///<param Name= "func" >json processing method delegate, returns a JSON-formatted string </param>///&LT;PA Ram Name= "Isfilternull" > whether to filter null objects in Ienumerable<tsource> source, default to True</param>//<returnS> standard JSON-formatted string </returns> private static string delegatetojson<tsource> (Ienumerable<tsource> s                Ource, func<tsource[], string> Func, bool Isfilternull = True) {if (source = = null) {            return Emptyjson;            } tsource[] Enumerable; if (isfilternull) {//filter null enumerable = source. Where (t = = null).            ToArray ();                } else {//does not filter null, but the upper layer needs to be aware that there are null objects inside, which can cause a where or select to throw 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 default filter null                Object var list1 = new List<test> {new Test {Id = ten, Type = $, name= "Allen"}, New Test {id = one, type = $}, new Test {id = +, Type = +}, new Test {id = 13            , type = $, name= "Peter"}, NULL, new Test {Id = +, Type = $, name=null}}; Specifies the properties required for JSON data string jsonstring = List1. ToJson (t = new {id = t.id, type = T.type}); Recommended notation, even true is omitted//string jsonstring = Jsonhelper.tojson (list1, t = = new {id = t.id, type = T.type}); The wording//string jsonstring = List1 is not recommended.            ToJson (t = new {id = t.id, type = T.type}, True);            Console.WriteLine (jsonstring); Filter out the object named "Allen" string jsonString2 = List1. ToJson (t = T.name = = "Allen"); Recommended notation, even true is omitted//sTring jsonString2 = Jsonhelper.tojson (list1, t = = T.name = "Allen"); The wording//string JsonString2 = List1 is not recommended.            ToJson (t = = T.name = = "Allen", true);            Console.WriteLine (JSONSTRING2); Filter out the object named "Allen", and specify the properties required for JSON data string jsonString3 = List1. ToJson (t = T.name = = "Allen", t = = new {id = t.id, type = T.type}); Recommended notation, even true omitted//string jsonString3 = Jsonhelper.tojson (list1, t = = T.name = "Allen", t = = new {id = T.id, type = T.type}); The wording//string JsonString3 = List1 is not recommended.            ToJson (t = = = T.name = "Allen", t = = new {id = t.id, type = T.type}, True);            Console.WriteLine (JSONSTRING3); #endregion #region do not filter null object var list2 = new List<test> {new Test { id = ten, type = $, name= "Allen"}, new test {Id = one, type = Name=, "Bolong"}, new test {I D = name=, Type = 23°c, "Popo"}, New TeSt {id = +, type = $, name= "Peter"}, new Test {id = +, type = +, name= "Willy"}}; Specifies the properties required for JSON data string jsonString4 = List2.            ToJson (t = new {id = t.id, type = T.type}, False);            Console.WriteLine (JSONSTRING4); Filter out the object named "Allen" string jsonString5 = List2.            ToJson (t = = T.name = = "Allen", false);            Console.WriteLine (JSONSTRING5); Filter out the object named "Allen", and specify the properties required for JSON data 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<t            Est>> ();            list<test> testList2 = jsonstring2.fromjson<list<test>> ();            Test test = jsonstring3.fromjson<test> (); Weak type Test var test2 = jsonstring.frOmjson ();            Newtonsoft.Json.Linq.JArray test3 = test2;        Console.readkey ();        }} internal class Test {public int Type {get; set;}        public int Id {get; set;}    public string Name {get; set;} }

PS: Is there a better package proposal?

JSON extension class--jsonhelper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.