微信开发之工具类
微信开发过程中少不了一些数据类型的转换,其中json格式用的最多,所以就有了下面这一段代码:
public static string toJson(this object jsonObj) { try { return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(jsonObj); } catch (Exception ex) { LogHelper.write("toJson:" + ex.Message + ",data:" + DateTime.Now); return null; } } public static T fromJson<T>(this string json) where T : class { return new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<T>(json); }
当然,要引用Microsoft.JScript。
期间也要用到时间戳之间的转换:
public static int dateToInt(this DateTime time) { int intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); intResult = Convert.ToInt32((time - startTime).TotalSeconds); return intResult; } public static DateTime intToDate(this int timeStamp) { DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dateTimeStart.Add(toNow); }
还有一些常用的方法,例如,字符串转数字:
public static int toInt(this string str) { int result = 0; int.TryParse(str, out result); return result; }