JSON帮助类

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Reflection;

/// <summary>
    /// JSON帮助类
    /// </summary>
public class JSONHelper
{

    


    /// <summary>
    /// 对象转JSON
    /// </summary>
    /// <param name="obj">对象</param>
    /// <returns>JSON格式的字符串</returns>
    public static string ObjectToJSON(object obj)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = Int32.MaxValue;
        try
        {
            return jss.Serialize(obj);
        }
        catch (Exception ex)
        {

            throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
        }
    }
    /// <summary>
    /// 
    /// 同時將時間轉為 yyyy-MM-dd HH:mm:ss 格式
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ObjectToJSONConvertDate(object obj)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            string json = jss.Serialize(obj);
            string p = @"\\/Date\((-*\d+)\)\\/";
            System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateString2);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
            json = reg.Replace(json, matchEvaluator);
            return json;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }
    /// <summary>
    /// 
    /// 同時將時間轉為 yyyy-MM-dd 格式
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ObjectToJSONDate(object obj)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            string json = jss.Serialize(obj);
            string p = @"\\/Date\((-*\d+)\)\\/";
            System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDate);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
            json = reg.Replace(json, matchEvaluator);
            return json;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }
    private static string ConvertJsonDateToDate(System.Text.RegularExpressions.Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[0].Value.ToString().Replace("\\/Date(", "").Replace(")\\/", "")));
        dt = dt.ToLocalTime();
        result = dt.ToString("yyyy-MM-dd");
        return result;
    }

    /// <summary>
    /// 数据表转键值对集合
    /// 把DataTable转成 List集合, 存每一行
    /// 集合中放的是键值对字典,存每一列
    /// </summary>
    /// <param name="dt">数据表</param>
    /// <returns>哈希表数组</returns>
    public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
    {
        List<Dictionary<string, object>> list
             = new List<Dictionary<string, object>>();

        foreach (DataRow dr in dt.Rows)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (DataColumn dc in dt.Columns)
            {
                dic.Add(dc.ColumnName, dr[dc.ColumnName]);
            }
            list.Add(dic);
        }
        return list;
    }

    /// <summary>
    /// 数据集转键值对数组字典
    /// </summary>
    /// <param name="dataSet">数据集</param>
    /// <returns>键值对数组字典</returns>
    public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
    {
        Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();

        foreach (DataTable dt in ds.Tables)
            result.Add(dt.TableName, DataTableToList(dt));

        return result;
    }

    /// <summary>
    /// 数据表转JSON
    /// </summary>
    /// <param name="dataTable">数据表</param>
    /// <returns>JSON字符串</returns>
    public static string DataTableToJSON(DataTable dt)
    {
        return ObjectToJSON(DataTableToList(dt));
    }
     /// <summary>
    /// 数据表转JSON;同時將時間轉為 yyyy-MM-dd HH:mm:ss 格式
    /// </summary>
    /// <param name="dataTable">数据表</param>
    /// <returns>JSON字符串</returns>
    public static string DataTableToJSONConvertDate(DataTable dt)
    {
        return ObjectToJSONConvertDate(DataTableToList(dt));
    }
    /// <summary>
    /// 数据表转JSON;同時將時間轉為 yyyy-MM-dd 格式
    /// </summary>
    /// <param name="dataTable">数据表</param>
    /// <returns>JSON字符串</returns>
    public static string DataTableToJSONDate(DataTable dt)
    {
        return ObjectToJSONDate(DataTableToList(dt));
    }
    /// <summary>
    /// JSON文本转对象,泛型方法
    /// </summary>
    /// <typeparam name="T">类型</typeparam>
    /// <param name="jsonText">JSON文本</param>
    /// <returns>指定类型的对象</returns>
    public static T JSONToObject<T>(string jsonText)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            jss.MaxJsonLength = 5097152; //
            return jss.Deserialize<T>(ConvertJsonDate(jsonText));
        }
        catch (Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
        }
    } 

    /// <summary>
    /// 将JSON文本转换为数据表数据
    /// </summary>
    /// <param name="jsonText">JSON文本</param>
    /// <returns>数据表字典</returns>
    /// 
    public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
    {
        return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
    }

    /// <summary>
    /// 将JSON文本转换成数据行
    /// </summary>
    /// <param name="jsonText">JSON文本</param>
    /// <returns>数据行的字典</returns>
    public static Dictionary<string, object> DataRowFromJSON(string jsonText)
    {
        return JSONToObject<Dictionary<string, object>>(jsonText);
    }

    /// <summary> 
    /// DataTable转Json 
    /// </summary> 
    /// <param name="dtb"></param> 
    /// <returns></returns> 
    public static string Dtb2Json(DataTable dtb)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        ArrayList dic = new ArrayList();
        foreach (DataRow row in dtb.Rows)
        {
            Dictionary<string, object> drow = new Dictionary<string, object>();
            foreach (DataColumn col in dtb.Columns)
            {
                drow.Add(col.ColumnName, row[col.ColumnName]);
            }
            dic.Add(drow);
        }
        return jss.Serialize(dic);
    }

    /// <summary> 
    /// DataTable转Json 
    /// </summary> 
    /// <param name="dtb"></param> 
    /// <param name="count"></param>   
    /// <returns></returns> 
    public static string Dtb2Json(DataTable dtb, int count)
    {
        if (dtb == null || dtb.Rows.Count == 0)
            return "{\"total\":0}";
        else
        {
            string json = Dtb2Json(dtb);
            if (json.Trim().Length > 0)
            {
                json = "{\"total\":" + count.ToString() + ",\"rows\":[" + json.Substring(1) + "}";
            }
            return json;
        }
    }

    /// <summary> 
    /// Json转DataTable 
    /// </summary> 
    /// <param name="json"></param> 
    /// <returns></returns> 
    public static DataTable Json2Dtb(string json)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        ArrayList dic = jss.Deserialize<ArrayList>(json);
        DataTable dtb = new DataTable();
        if (dic.Count > 0)
        {
            foreach (Dictionary<string, object> drow in dic)
            {
                if (dtb.Columns.Count == 0)
                {
                    foreach (string key in drow.Keys)
                    {
                        if (drow[key] == null)
                        {
                            Type tempT = null;
                            foreach (Dictionary<string, object> drow2 in dic)
                            {

                                foreach (string key2 in drow2.Keys)
                                {
                                    if (drow2[key2] != null && key2 == key)
                                    {
                                        tempT = drow2[key2].GetType();
                                        break;
                                    }
                                }
                                if (tempT != null)
                                    break;
                            }
                            if (tempT != null)
                                dtb.Columns.Add(key, tempT);
                            else
                                dtb.Columns.Add(key, System.Type.Missing.GetType());
                        }
                        else
                        {
                            //更正当第一行数据为int,后面数据为小数时取整
                            if (drow[key].GetType() == typeof(int))
                                dtb.Columns.Add(key, typeof(decimal));
                            else
                                dtb.Columns.Add(key, drow[key].GetType());
                        }
                    }
                }
                DataRow row = dtb.NewRow();
                foreach (string key in drow.Keys)
                {
                    row[key] = drow[key];
                }
                dtb.Rows.Add(row);
            }
        }
        return dtb;
    }

    /// <summary>   
    /// List转成json    
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="jsonName"></param>   
    /// <param name="list"></param>   
    /// <param name="count"></param>   
    /// <returns></returns>
    public static string ListToJson<T>(IList<T> list, string jsonName, int count)
    {
        if (list == null || list.Count == 0)
            return "{\"total\":0}";

        string json = ListToJson<T>(list, jsonName);
        if (json.Trim().Length > 0)
        {
            json = "{ \"total\":" + count.ToString() + "," + json.Substring(1);
        }
        json.Replace("\r\n", "");
        return json;
    }
    /// <summary>
    /// List转成json 
    /// 同時將時間轉為 yyyy-MM-dd HH:mm:ss 格式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="jsonName"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public static string ListToJsonAndConvertDate<T>(IList<T> list, string jsonName, int count)
    {
        if (list == null || list.Count == 0)
            return "{\"total\":0,\"" + jsonName + "\":[]}";//增加jsonName:[] 没有jsonName填充的datagrid appenRow会出错

        string json = ListToJson<T>(list, jsonName);
        if (json.Trim().Length > 0)
        {
            json = "{ \"total\":" + count.ToString() + "," + json.Substring(1);
        }
        string p = @"\\/Date\((-*\d+)\)\\/";
        System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateString2);
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
        json = reg.Replace(json, matchEvaluator);
        json.Replace("\r\n", "");
        return json;
    }
  
    private static string ConvertJsonDateToDateString2(System.Text.RegularExpressions.Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[0].Value.ToString().Replace("\\/Date(", "").Replace(")\\/", "")));
        dt = dt.ToLocalTime();
        result = dt.ToString("yyyy-MM-dd HH:mm:ss");
        return result;
    }
 
    /// <summary>   
    /// List转成json    
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="jsonName"></param>   
    /// <param name="list"></param>   
    /// <returns></returns>
    public static string ListToJson<T>(IList<T> list, string jsonName)
    {
        if (list == null || list.Count == 0)
            return "{}";

        StringBuilder Json = new StringBuilder();
        if (jsonName == "")
            Json.Append("[");
        else if (string.IsNullOrEmpty(jsonName))
            jsonName = "{\"" + list[0].GetType().Name + "\":[";
        else
            Json.Append("{\"" + jsonName + "\":[");
        if (list.Count > 0)
        {
            for (int i = 0; i < list.Count; i++)
            {               
                Json.Append(JSONHelper.ObjectToJSON(list[i]));
                if (i < list.Count - 1)
                {
                    Json.AppendLine(",");
                }
            }
        }
        Json.Append("]");
        if (jsonName != "")
            Json.Append("}");
        Json.Replace("\r\n", "");
        return Json.ToString();
    }

    /// <summary>   
    /// List转成json    
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="list"></param>   
    /// <returns></returns>   
    public static string ListToJson<T>(IList<T> list)
    {
        if (list == null || list.Count == 0)
            return "{}";

        object obj = list[0];
        return ListToJson<T>(list, obj.GetType().Name);
    }

    /// <summary>   
    /// List转成json 并带有没资料提示    WILSON
    /// </summary>   
    /// <typeparam name="T"></typeparam>   
    /// <param name="list"></param>   
    /// <returns></returns>   
    public static string ListToJsonByWilson<T>(IList<T> list, string jsonName)
    {
        string json = "";
        if (list.Count > 0)
        {
            json = JSONHelper.ListToJson<T>(list, jsonName);
            json = "[" + json.Insert(1, "\"status\":\"1\",") + "]";
        }
        else
            json = "[{\"status\":\"-1\",\"msg\":\"沒有符合條件的數據\"}]";
        json.Replace("\r\n", "");
        return json;
    }

    public static string ListToJsonByWilsonTrad<T>(IList<T> list, string jsonName)
    {
        string json = "";
        if (list.Count > 0)
        {
            json = JSONHelper.ListToJson<T>(list, jsonName);
            json = "[" + json.Insert(1, "\"status\":\"1\",") + "]";
        }
        else
            json = "[{\"status\":\"-1\",\"msg\":\"沒有符合條件的數據\"}]";
        json.Replace("\r\n", "");
        return Wilson.util.GeneralLib.SimplifiedToTraditional(json);
    }

    public static string ObjToJsonByWilson(object obj)
    {
        if (obj == null)
            return "";

        string json = "";
        json = JSONHelper.ObjectToJSON(obj);
        json = "[" + json.Insert(1, "\"status\":\"1\",") + "]";

        if (json.EndsWith(","))
            json = json.Substring(0, json.Length - 1);
        //json = json.Replace("[]", "");

        return json;
    }

    public static string ConvertJsonDate(string Json)
    {
        string p = @"/Date\(\-?\d+\)/";
        System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateString);
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
        return reg.Replace(Json, matchEvaluator);       
      
    }
    private static string ConvertJsonDateToDateString(System.Text.RegularExpressions.Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[0].Value.ToString().Replace("/Date(", "").Replace(")/", "")));
        dt = dt.ToLocalTime();
        result = dt.ToString("yyyy-MM-dd HH:mm:ss");
        return result;
    }
    public static string ConvertJsonDate2(string Json)
    {
        string p = @"\\/Date\(\-?\d+\)\\/";
        System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateString2);
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
        return reg.Replace(Json, matchEvaluator);

    }
    public static string GetJsonEnum(Type enumType)
    {
        return GetJsonEnum(enumType, null);
    }

    public static string GetJsonEnum(Type enumType, string alias)
    {
        int[] values = (int[])Enum.GetValues(enumType);
        string[] names = Enum.GetNames(enumType);
        string[] pairs = new string[values.Length];

        for (int i = 0; i < values.Length; i++)
        {
            pairs[i] = names[i] + ": " + values[i];
        }

        if (string.IsNullOrEmpty(alias))
            alias = enumType.Name;

        return string.Format("var {0}={{\n{1}\n}}", alias, string.Join(",\n", pairs));
    }

    public static string string2Json(string s)
    {
        string newstr = "";
        int len = s.Length;
        for (int i = 0; i < len; i++)
        {
            char[] c = s.ToCharArray();
            switch (c[i])
            {
                case '\"':
                    {
                        newstr += "\\\"";
                        break;
                    }
                case '\\':
                    {
                        newstr += "\\\\";
                        break;
                    }
                case '/':
                    {
                        newstr += "\\/";
                        break;
                    }
                case '\b':
                    {
                        newstr += "\\b";
                        break;
                    }
                case '\f':
                    {
                        newstr += "\\f";
                        break;
                    }
                case '\n':
                    {
                        newstr += "\\n";
                        break;
                    }
                case '\r':
                    {
                        newstr += "\\r";
                        break;
                    }
                case '\t':
                    {
                        newstr += "\\t";
                        break;
                    }
                default:
                    {
                        newstr += c[i].ToString();
                        break;
                    }
            }
        }
        return newstr;
    }

    /// <summary>
    /// 
    /// 同時將時間轉為 yyyy-MM-dd格式
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ObjectToJSONConvertDateShort(object obj)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        try
        {
            string json = jss.Serialize(obj);
            string p = @"\\/Date\((-*\d+)\)\\/";
            System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateStringShort);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
            json = reg.Replace(json, matchEvaluator);
            return json;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    private static string ConvertJsonDateToDateStringShort(System.Text.RegularExpressions.Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[0].Value.ToString().Replace("\\/Date(", "").Replace(")\\/", "")));
        dt = dt.ToLocalTime();
        result = dt.ToString("yyyy-MM-dd");
        return result;
    }


    /// <summary>
    /// List转成json 
    /// 同時將時間轉為 yyyy-MM-dd HH:mm:ss 格式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="jsonName"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public static string ListToJsonAndConvertDateShort<T>(IList<T> list, string jsonName, int count)
    {
        if (list == null || list.Count == 0)
            return "{\"total\":0}";

        string json = ListToJson<T>(list, jsonName);
        if (json.Trim().Length > 0)
        {
            json = "{ \"total\":" + count.ToString() + "," + json.Substring(1);
        }

       //只获取正整数部分,不考虑大于1970年问题  
       //string p = @"\\/Date(\d+)\\/";  
      //考虑小于1970年的问题  
    
       string p = @"\\/Date\((-*\d+)\)\\/";
        System.Text.RegularExpressions.MatchEvaluator matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDateString2Short);
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);
        json = reg.Replace(json, matchEvaluator);
        json.Replace("\r\n", "");
        return json;
    }

    private static string ConvertJsonDateToDateString2Short(System.Text.RegularExpressions.Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); 
        //dt = dt.AddMilliseconds(long.Parse(m.Groups[0].Value.ToString().Replace("\\/Date(", "").Replace(")\\/", "")));
        dt = dt.ToLocalTime();
        result = dt.ToString("yyyy-MM-dd");
        return result;
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值