1. 程式人生 > >C#資料來源轉json

C#資料來源轉json

  public class ToJson
    {//DataTable轉成Json
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jsonName"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public  string DataTableToJson(string jsonName, DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            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++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        /// <summary>
        /// List轉成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonName"></param>
        /// <param name="IL"></param>
        /// <returns></returns>
        public string ObjectToJson<T>(string jsonName, IList<T> IL)
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{\"" + jsonName + "\":[");
            if (IL.Count > 0)
            {
                for (int i = 0; i < IL.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    Type type = obj.GetType();
                    PropertyInfo[] pis = type.GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pis.Length; j++)
                    {
                        Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + pis[j].GetValue(IL[i], null) + "\"");
                        if (j < pis.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < IL.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        /// <summary>
        /// 物件轉換為Json字串
        /// </summary>
        /// <param name="jsonObject">物件</param>
        /// <returns>Json字串</returns>
        public  string objectToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                string value = string.Empty;
                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                {
                    //  value = "'" + objectValue.ToString() + "'";
                        value = '"' + objectValue.ToString() + '"';
                    //  value =objectValue.ToString();
                }
                else if (objectValue is string)
                {
                    // value = "'" + stringToJson(objectValue.ToString()) + "'";
                       value = '"' + stringToJson(objectValue.ToString())+ '"' ;
                    // value = stringToJson(objectValue.ToString()) ;
                }
                else if (objectValue is IEnumerable)
                {
                    value = ArrayToJson((IEnumerable)objectValue);
                }
                else
                {
                    value = stringToJson(objectValue.ToString());
                }
                jsonString += "\"" + stringToJson(propertyInfo[i].Name) + "\":" + value + ",";
            }
            return DeleteLast(jsonString) + "}";
        }
        /// <summary>
        /// 物件集合轉換Json
        /// </summary>
        /// <param name="array">集合物件</param>
        /// <returns>Json字串</returns>
        public  string ArrayToJson(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString += objectToJson(item) + ",";
            }
            return DeleteLast(jsonString) + "]";
        }
        /// <summary>
        /// 普通集合轉換Json
        /// </summary>
        /// <param name="array">集合物件</param>
        /// <returns>Json字串</returns>
        public  string ToArrayString(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString = stringToJson(item.ToString()) + ",";
            }
            return DeleteLast(jsonString) + "]";
        }
        /// <summary>
        /// 刪除結尾字元
        /// </summary>
        /// <param name="str">需要刪除的字元</param>
        /// <returns>完成後的字串</returns>
        private  string DeleteLast(string str)
        {
            if (str.Length > 1)
            {
                return str.Substring(0, str.Length - 1);
            }
            return str;
        }
        /// <summary>
        /// String轉換為Json
        /// </summary>
        /// <param name="value">String物件</param>
        /// <returns>Json字串</returns>
        public  string stringToJson(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }
            string temstr;
            temstr = value;
            temstr = temstr.Replace("{", "{").Replace("}", "}").Replace(":", ":").Replace(",", ",").Replace("[", "【").Replace("]", "】").Replace(";", ";").Replace("\n", "<br/>").Replace("\r", "");
            temstr = temstr.Replace("\t", "  ");
            temstr = temstr.Replace("'", "\'");
            temstr = temstr.Replace(@"\", @"\\");
            temstr = temstr.Replace("\"", "\"\"");
            return temstr;
        }
    }