Go to my github

开发日记: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;
    }

  

posted @ 2018-11-17 10:52  峡谷少爷  阅读(225)  评论(0编辑  收藏  举报