C#中Json和List/DataSet相互转换

       #region List<T> 转 Json
        /// <summary>
        /// List<T> 转 Json
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="Obj">List<T>对象</param>
        /// <returns></returns>
        public static string ObjectToJson<T>(T obj)
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                //转换失败
                return null;
            }
        }
        #endregion

        #region Json 转 List<T>
        /// <summary>
        /// Json 转 List<T>
        /// </summary>
        /// <param name="json">待转换字符串</param>
        /// <param name="t">Json被转换类型</param>
        /// <returns></returns>
        public static Object JsonToObject(string json, Type t)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(t);
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    return serializer.ReadObject(ms);
                }
            }
            catch
            {
                //转换失败
                return null;
            }
        }
        #endregion

        #region DataTable 转Json
        /// <summary>
        /// DataTable 转Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            try
            {
                jsonBuilder.Append("[");//转换成多个model的形式
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    jsonBuilder.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        jsonBuilder.Append("\"");
                        jsonBuilder.Append(dt.Columns[j].ColumnName);
                        jsonBuilder.Append("\":\"");
                        jsonBuilder.Append(dt.Rows[i][j].ToString());
                        jsonBuilder.Append("\",");
                    }
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
            }
            catch (Exception ex)
            {
                //TODO
                throw new Exception(ex.Message);
            }
            return jsonBuilder.ToString();
        }
        #endregion

        #region 将DataSet转Json
        /// <summary>
        /// 将DataSet转化成JSON数据
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string DataSetToJson(DataSet ds)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            try
            {
                jsonBuilder.Append("[");
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    jsonBuilder.AppendFormat("T{0}:[", (i + 1));
                    for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                    {
                        jsonBuilder.Append("{");
                        for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
                        {
                            jsonBuilder.AppendFormat("{0}:{1}", ds.Tables[i].Columns[k].ColumnName, ds.Tables[i].Rows[j][k].ToString());
                            if (k != ds.Tables[i].Columns.Count - 1)
                                jsonBuilder.Append(",");
                        }
                        jsonBuilder.Append("}");
                        if (j != ds.Tables[i].Rows.Count - 1)
                            jsonBuilder.Append(",");
                    }
                    jsonBuilder.Append("]");
                    if (i != ds.Tables.Count - 1)
                        jsonBuilder.Append(",");
                }
                jsonBuilder.Append("]");
            }
            catch (Exception ex)
            {
                //TODO
                throw new Exception(ex.Message);
            }
            return jsonBuilder.ToString();
        }
        #endregion

posted @ 2013-08-12 16:32  永不言败,自信相伴  阅读(2019)  评论(0编辑  收藏  举报