一个实用的Json数据转换封装的帮助类 JsonHelper

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
{
    /// 
    /// Json数据转换封装
    /// 
    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(sJason); 
         */
        /// 
        /// 将时间由"\/Date(10000000000-0700)\/" 格式转换成 "yyyy-MM-dd HH:mm:ss" 格式的字符串
        /// 
        /// 
        /// 
        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;
        }
        /// 
        /// 将时间由 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换成"\/Date(10000000000-0700)\/" 格式
        /// 
        /// 
        /// 
        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;
        }
        /// 
        /// 扩展Object 方法 ToJson
        /// 
        /// 
        /// 
        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;
        }

        /// 
        /// Jason deSerialize
        /// 
        /// 
        /// 
        /// 
        public static T FromJson(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();
        }
    }
}

你可能感兴趣的:(JsonHelper)