1. 程式人生 > >開發日記:JsonCSharpHelp

開發日記:JsonCSharpHelp

 

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;

  

 public  static class JsonCSharpHelp
    {
        /// <summary>
        /// 取得某個Json value
        /// </summary>
        /// <param name="JsonString">{Name:aaaaa,Value:aaaa}</param>
        /// <param name="tagName"></param>
        /// <returns></returns>
        public static string GetJsonValue(string JsonString,string tagName)
        {
            JsonString = JsonString.TrimStart('{');
            JsonString = JsonString.TrimEnd('}');
            string[] splts = JsonString.Split(',');
            foreach (string tmp in splts)
            {
                if (tmp != string.Empty)
                {
                    string[] tag = tmp.Split(':');
                    if (tag[0] == tagName) return tag[1];                
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 獲取系統字典裡的json物件集合
        /// json物件集合格式:[{"key":"1","value":"default"},{"key":"2","value":"default1"},{"key":"3","value":"default2"}]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="JsonStr"></param>
        /// <returns></returns>
        public static List<T> JSONStringToList<T>(this string JsonStr)
        {

            /*JavaScriptSerializer Serializer = new JavaScriptSerializer();

            List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);

            return objs;*/


            return JsonConvert.DeserializeObject<List<T>>(JsonStr);
        }

        /// <summary>
        /// 把json字串轉成物件
        /// </summary>
        /// <typeparam name="T">物件</typeparam>
        /// <param name="data">json字串</param> 
        public static T JSONStringToObj<T>(string data)
        {
           /* JavaScriptSerializer json = new JavaScriptSerializer();
            return json.Deserialize<T>(data);*/

            return JsonConvert.DeserializeObject<T>(data);
        }

        /// <summary>
        /// 把物件轉成json字串
        /// </summary>
        /// <param name="o">物件</param>
        /// <returns>json字串</returns>
        public static string ObjToJSONString(object o)
        {
            /*System.Text.StringBuilder sb = new System.Text.StringBuilder();
            JavaScriptSerializer json = new JavaScriptSerializer();
            json.Serialize(o, sb);
            return sb.ToString();*/
           // return JsonConvert.SerializeObject(o, new DataTableConverter());
            /*var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            var json = JsonConvert.SerializeObject(response, Formatting.Indented, jSetting);*/
            return JsonConvert.SerializeObject(o, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-dd hh:mm:ss"});
        }

        /// <summary>
        /// 將原表型別為decimal型別的資料改為string型別
        /// </summary>
        /// <param name="argDataTable"></param>
        /// <returns></returns>
        public static DataTable ModifyDataTableColumnType(DataTable argDataTable)
        {
            bool bl = false;
            DataTable dtResult = new DataTable();
            //克隆表結構
            dtResult = argDataTable.Clone();
            foreach (DataColumn col in dtResult.Columns)
            {
                if (col.DataType == typeof(decimal))
                {
                    //修改列型別
                    col.DataType = typeof(String);
                    bl = true;
                }
            }
            if (bl)
            {
                foreach (DataRow row in argDataTable.Rows)
                {
                    DataRow rowNew = dtResult.NewRow();
                    rowNew.ItemArray = row.ItemArray;
                    dtResult.Rows.Add(rowNew);
                }
                return dtResult;
            }
            return argDataTable;
        } 



        /// <summary>
        /// 傳入jsong串,獲取匹配key的value值
        /// </summary>
        /// <param name="JsonStr"></param>
        /// <param name="matchKey"></param>
        /// <returns></returns>
        public static string GetSysParamValueByKey(string JsonStr, string matchKey)
        {
            string strResult = "";
            IList<SysParamJsonObj> list = JsonCSharpHelp.JSONStringToList<SysParamJsonObj>(JsonStr);
            foreach (SysParamJsonObj sysOjb in list)
            {
                if (sysOjb.key.ToUpper() == matchKey.ToUpper())
                {
                    strResult = sysOjb.value;
                    break;
                }
            }
            return strResult;
        }

        /// <summary>
        ///根據物件SysParamJsonObj列表獲取到某個key對應的value值
        /// </summary>
        /// <param name="list"></param>
        /// <param name="matchKey"></param>
        /// <returns></returns>
        public static string GetSysParamValueByKey(IList<SimpleParamObj> list, string matchKey)
        {
            string strResult = "";
            if (list == null) return strResult;
            foreach (SimpleParamObj sysOjb in list)
            {
                if (sysOjb.K.ToUpper() == matchKey.ToUpper())
                {
                    strResult = sysOjb.V;
                    break;
                }
            }
            return strResult;
        }

        /// <summary>
        /// 獲取一個類指定的屬性值
        /// </summary>
        /// <param name="info">json物件 "{\"3\":123,body:456,list:{title:'abc',body:'what'}}"</param>
        /// <param name="field">屬性名稱</param>
        /// <param name="erro">輸出錯誤資訊</param>
        /// <returns></returns>
        public static object GetPropertyValue(object info, string field, out string erro)
        {
            erro = string.Empty;
            if (info == null) return null;
            JObject jo = null;
            try
            {
                jo = JObject.Parse(info.ToString());
            }
            catch (Exception e)
            {
                erro = "傳入物件非json物件格式:" + e.Message;
                return null;
            }

            if (jo.Property(field) == null || jo.Property(field).ToString() == "")            
            {
                erro = "鍵值 " + field + " 不存在!";
                return null;         
            }
            return jo.Property(field).Value;
        }

        /// <summary>
        /// 獲取一個類指定的屬性值
        /// </summary>
        /// <param name="info">json物件 "{\"3\":123,body:456,list:{title:'abc',body:'what'}}"</param>
        /// <param name="field">屬性名稱</param>
        /// <param name="erro">輸出錯誤資訊</param>
        /// <returns></returns>
        public static Hashtable GetPropertyValue(object info, string[] fields)
        {
            Hashtable ht = new Hashtable();
          //  erro = string.Empty;
            if (info == null) return null;
          //  Type t = info.GetType();

            // info = "{\"3\":123,body:456,list:{title:'abc',body:'what'}}";           
           /* if (t != typeof(JObject))
            {
                erro = "傳入物件非json物件格式";
                return null;
            }*/
            JObject jo = null;
            try
            {
                jo = JObject.Parse(info.ToString());
            }
            catch (Exception e)
            {
               // erro = "傳入物件非json物件格式:" + e.Message;
                return null;
            }
            int len = fields.Length;
            object[] os = new object[len];
            IEnumerable<JProperty> properties = jo.Properties();
            int i = 0;
            bool bl = false;
            string f = string.Empty;
            for (i = 0; i < len; i++)
            {
                bl = false; 
                f = fields[i];
                foreach (JProperty item in properties)
                {
                    if (item.Name.ToUpper() == f.ToUpper())
                    {
                        ht.Add(f, item.Value);
                        //os[i] = item.Value;
                        bl = true;
                        break;
                    }
                }
                if (!bl)
                {
                    ht.Add(f, "");
                  //  erro = "沒有找到鍵值對匹配項" + f;
                   // return null;
                }
            }

            return ht;
        }


        /// <summary>   
        /// 將Json序列化的時間由/Date(1294499956278+0800)轉為字串   
        /// </summary>   
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }


        /// <summary>    
        /// 將時間字串轉為Json時間   
        /// </summary>   
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }


     /*   /// <summary>
        /// JSON序列化
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(pattern);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            return jsonString;
        }
        /// <summary>
        /// JSON反序列化
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T JsonDeserialize<T>(string jsonString)
        {
            string pattern = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(pattern);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
        */

        /// <summary>   
        /// Datatable轉換為Json   
        /// </summary>   
        /// <param name="table">Datatable物件</param>   
        /// <returns>Json字串</returns>   
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            if (jsonString.Length == 1)
            {
                return "[]";
            }
            return jsonString.ToString();
        }

        /// <summary>   
        /// Datatable轉換為Json   
        /// </summary>   
        /// <param name="table">Datatable物件</param>   
        /// <param name="dataCount">資料總量 分頁用</param>   
        /// <returns>Json字串</returns>   
        public static string ToJson(DataTable dt, int dataCount)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                jsonString.Append("\"DATA_COUNT\":" + dataCount + ",");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            if (jsonString.Length == 1)
            {
                return "[]";
            }
            return jsonString.ToString();
        }


        /// <summary>  
        /// DataTable轉成Json   
        /// </summary>  
        /// <param name="jsonName"></param>  
        /// <param name="dt"></param>  
        /// <returns></returns>  
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j] is DBNull ? string.Empty : dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        /// <summary>   
        /// DataReader轉換為Json   
        /// </summary>   
        /// <param name="dataReader">DataReader物件</param>   
        /// <returns>Json字串</returns>   
        public static string ToJson(IDataReader dataReader)
        {
            try
            {
                StringBuilder jsonString = new StringBuilder();
                jsonString.Append("[");
                while (dataReader.Read())
                {
                    jsonString.Append("{");
                    for (int i = 0; i < dataReader.FieldCount; i++)
                    {
                        Type type = dataReader.GetFieldType(i);
                        string strKey = dataReader.GetName(i);
                        string strValue = dataReader[i].ToString();
                        jsonString.Append("\"" + strKey + "\":");
                        strValue = StringFormat(strValue, type);
                        if (i < dataReader.FieldCount - 1)
                        {
                            jsonString.Append(strValue + ",");
                        }
                        else
                        {
                            jsonString.Append(strValue);
                        }
                    }
                    jsonString.Append("},");
                }
                if (!dataReader.IsClosed)
                {
                    dataReader.Close();
                }
                jsonString.Remove(jsonString.Length - 1, 1);
                jsonString.Append("]");
                if (jsonString.Length == 1)
                {
                    return "[]";
                }
                return jsonString.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>   
        /// DataSet轉換為Json   
        /// </summary>   
        /// <param name="dataSet">DataSet物件</param>   
        /// <returns>Json字串</returns>   
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }

        /// <summary>  
        /// 過濾特殊字元  
        /// </summary>  
        /// <param name="s"></param>  
        /// <returns></returns>  
        public static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    case '\v':
                        sb.Append("\\v"); break;
                    case '\0':
                        sb.Append("\\0"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }



        /// <summary>  
        /// 格式化字元型、日期型、布林型  
        /// </summary>  
        /// <param name="str"></param>  
        /// <param name="type"></param>  
        /// <returns></returns>  
        private static string StringFormat(string str, Type type)
        {
            if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type == typeof(byte[]))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(Guid))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }


    }

  

    /// <summary>
    /// json物件
    /// </summary>
    [Serializable]
    public class SysParamJsonObj
    {
        /// <summary>
        /// id
        /// </summary>
        public string key;

        /// <summary>
        /// value
        /// </summary>
        public string value;
    }