Public classJsonhelper { PublicJsonhelper () {// //Todo:add constructor Logic here// } /// <summary> ///serializes an object into a JSON string/// </summary> /// <typeparam name= "T" >Object Type</typeparam> /// <param name= "obj" >Object Entity</param> /// <returns>JSON string</returns> Public Static stringGetjson<t>(T obj) {//Remember to add references System.ServiceModel.Web /** * If you do not add the above reference, System.Runtime.Serialization.Json; JSON is not coming out of the OH **/DataContractJsonSerializer JSON=NewDataContractJsonSerializer (typeof(T)); using(MemoryStream ms =NewMemoryStream ()) {JSON. WriteObject (MS, obj); stringSzjson =Encoding.UTF8.GetString (Ms. ToArray ()); returnSzjson; } } /// <summary> ///To restore a JSON string to an object/// </summary> /// <typeparam name= "T" >Object Type</typeparam> /// <param name= "Szjson" >JSON string</param> /// <returns>Object Entity</returns> Public StaticT parseformjson<t> (stringSzjson) {T obj= activator.createinstance<t>(); using(MemoryStream ms =NewMemoryStream (Encoding.UTF8.GetBytes (Szjson))) {DataContractJsonSerializer DCJ=NewDataContractJsonSerializer (typeof(T)); return(T) DCJ. ReadObject (MS); } } }
// because the collection cannot be received in WebService, JSON is selected with the string receive. // Call: List<biz. t_exentrydetailmodel> Exdetailmodel Exdetailmodel = uped. Jsonhelper.parseformjson<list<biz. T_exentrydetailmodel>> (JSONSTR); // parsing JSON strings as classes // entity classes convert JSON strings to classes List<Models.ExEntryDetailModel> detailmodel =servers. Getexentrydetailmodel (...); string jsonstr = uped. Jsonhelper.getjson<list<models.exentrydetailmodel>> (Detailmodel);
C # JSON helper classes (interoperable)