一個實用的Json資料轉換封裝的幫助類 JsonHelper
阿新 • • 發佈:2018-12-20
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Json; using System.Text.RegularExpressions; namespace uility { /// <summary> /// Json資料轉換封裝 /// </summary> public static class JsonHelper { /* 利用.Net FrameWork3.5提供的Json庫實現C#與Json資料轉換時,對於Datetime型別的資料,生成格式如下資料 /Date(10000000000-0700)/ 不直觀,同時相當部分js庫無法直接使用.利用正則表示式替換成"yyyy-MM-dd HH:mm:ss"格式以便於使用 使用舉例: T t = new T(); String sJson =t.ToJson(); T t1 = JosonHelper.FromJson<T>(sJason); */ /// <summary> /// 將時間由"\/Date(10000000000-0700)\/" 格式轉換成 "yyyy-MM-dd HH:mm:ss" 格式的字串 /// </summary> /// <param name="m"></param> /// <returns></returns> private static string GetDatetimeString(Match m) { string sRet = ""; try { System.DateTime dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); dt = dt.ToLocalTime(); sRet = dt.ToString("yyyy-MM-dd HH:mm:ss"); } catch { } return sRet; } /// <summary> /// 將時間由 "yyyy-MM-dd HH:mm:ss" 格式的字串轉換成"\/Date(10000000000-0700)\/" 格式 /// </summary> /// <param name="m"></param> /// <returns></returns> private static string GetDatetimeJson(Match m) { String sRet = ""; try { DateTime dt = DateTime.Parse(m.Groups[1].Value); dt = dt.ToUniversalTime(); TimeSpan ts = dt - DateTime.Parse("1970-01-01"); sRet = string.Format("\\/Date({0}{1})\\/", ts.TotalMilliseconds, TimeZoneString()); } catch { } return sRet; } /// <summary> /// 擴充套件Object 方法 ToJson /// </summary> /// <param name="obj"></param> /// <returns></returns> public static String ToJson(this object obj) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); jsonSerializer.WriteObject(ms, obj); String sRet = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); //將時間由"\/Date(10000000000-0700)\/" 格式轉換成 "yyyy-MM-dd HH:mm:ss" 格式的字串 string sPattern = @"\\/Date\((\d+)[+-]\d+\)\\/"; MatchEvaluator myMatchEvaluator = new MatchEvaluator(GetDatetimeString); Regex reg = new Regex(sPattern); sRet = reg.Replace(sRet, myMatchEvaluator); return sRet; } /// <summary> /// Jason deSerialize /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sJasonData"></param> /// <returns></returns> public static T FromJson<T>(String sJasonData) { //將時間由 "yyyy-MM-dd HH:mm:ss" 格式的字串轉換成"\/Date(10000000000-0700)\/" 格式 string sPattern = @"(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})"; MatchEvaluator myMatchEvaluator = new MatchEvaluator(GetDatetimeJson); Regex reg = new Regex(sPattern); string src = reg.Replace(sJasonData, myMatchEvaluator); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T)); //MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(src)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sJasonData)); T obj = (T)jsonSerializer.ReadObject(ms); ms.Close(); return obj; } private static string TimeZoneString() { return DateTimeOffset.Now.ToString() .Substring(DateTimeOffset.Now.ToString().LastIndexOf(" ")) .Replace(":", "").Trim(); } } }