///<summary> ///JSON Tool class ///</summary> Public classjsonutility {Private StaticJsonutility _instance =Newjsonutility (); ///<summary> ///Single Case ///</summary> Public Staticjsonutility Instance {get {return_instance;} set {_instance=value;} } ///<summary> ///JSON Goto object ///</summary> ///<typeparam name= "T" ></typeparam> ///<param name= "JSON" ></param> ///<returns></returns> PublicT jsontoobject<t>(String json) {var ser=NewDataContractJsonSerializer (typeof (T)); var ms=NewMemoryStream (Encoding.UTF8.GetBytes (JSON)); var jsonobject=(T) ser. ReadObject (MS); Ms. Close (); returnJsonobject; } ///<summary> ///JSON to Object list ///</summary> ///<typeparam name= "T" ></typeparam> ///<param name= "JSON" ></param> ///<returns></returns> PublicIlist<t> jsontoobjectlist<t>(String json) {JSON= json. Replace ("}]}", ""); var startIndex= json. IndexOf (": [{") + 3; var Newjson=JSON. Substring (StartIndex); var regex=NewRegex ("},{"); var jsons=regex. Split (Newjson); if(Newjson.contains ("\": []} ")) { Throw NewException ("The express number is not found"); } var list=NewList<t>(); foreach (var item in jsons) {var temp= "{" + Item + "}"; List. ADD (Jsontoobject<T>(temp)); } returnlist; } ///<summary> ///object to JSON ///</summary> ///<param name= "obj" ></param> ///<returns></returns> Publicstring Objecttojson (Object obj) {var serializer=NewDataContractJsonSerializer (obj. GetType ()); using (var ms=NewMemoryStream ()) {Serializer. WriteObject (MS, obj); var sb=NewStringBuilder (); Sb. Append (Encoding.UTF8.GetString (Ms. ToArray ())); returnsb. ToString (); } } ///<summary> ///Object List goto JSON ///</summary> ///<typeparam name= "T" ></typeparam> ///<param name= "ObjectList" ></param> ///<returns></returns> PublicString Objectlisttojson<t> (ilist<t>objectList) { returnObjectlisttojson (ObjectList, ""); } ///<summary> ///Object List goto JSON ///</summary> ///<typeparam name= "T" ></typeparam> ///<param name= "ObjectList" ></param> ///<param name= "ClassName" ></param> ///<returns></returns> PublicString Objectlisttojson<t> (ilist<t>objectList, String className) {var sbresult=NewStringBuilder (); Sbresult.append ("{"); ClassName= String. IsNullOrEmpty (className)? Objectlist[0]. GetType (). Name:classname; Sbresult.append ("\" "+ ClassName +" \ ": ["); for(var i = 0; i < Objectlist.count; i++) {var item=Objectlist[i]; if(I > 0) {sbresult.append (","); } sbresult.append (Objecttojson (item)); } sbresult.append ("]}"); returnsbresult.tostring (); } }
Programming Questions: 1. var person = ' {name: ' Lily ', Sex: ' Famale ', age:24,country: ' US '} '; converts person to JSON object and facilitates each property value.