.net Json JavaScriptSerializer JsonHelper类

结合.net 的JavaScriptSerializer 类实现Json数据处理

调用1:

     Model.Users m = BLL.UsersBLL.GetUserById(Convert.ToInt32(id));

        string result = "";

        if (m != null)
            result = JsonHelper.ObjectToJSON(m);

        context.Response.Write(result);    

调用2:

    Hashtable ht = new Hashtable();
        List<Model.UsersModel> resultlist = BLL.UsersBLL.GetUsersList(type, begin, end, page, 4, ht);

        string result = JsonHelper.ObjectToJSON(
            new
            {
                @list = resultlist,
                @today = DateTime.Now.ToString("yyyy-MM-dd"),
                @pageIndex = page,
                @recordCount = ht["rowcount"],
                @pageCount = ht["pagecount"]
            });
        context.Response.Write(result);//////////////////////////////////////////////////////////前台JS调用Json数据

$.ajax({
url: "../handler/zeji.ashx",
type: "POST",
data: "type=" + type + "&time=" + time + "&page=" + page,
//completed: $("#indicator").hide(),
success: function (data) {
data = eval("(" + data + ")");

for (var i = 0; i < data.list.length; i++) {

   var riqi = data.list[i].Riqi.toString();

}

var recordCount = data.recordCount;

}

});

 

JsonHelper 类

public class JsonHelper
{
    #region 私有方法
    /// <summary>
    /// 过滤特殊字符
    /// </summary>
    private static string StringToJson(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;
                default:
                    sb.Append(c); break;
            }
        }
        return sb.ToString();
    }

    /// <summary>
    /// 格式化字符型、日期型、布尔型
    /// </summary>
    private static string StringFormat(string str, Type type)
    {
        if (type == typeof(string))
        {
            str = StringToJson(str);
            str = "\"" + str + "\"";
        }
        else if (type == typeof(DateTime))
        {
            str = "\"" + str + "\"";
        }
        else if (type == typeof(bool))
        {
            str = str.ToLower();
        }
        else if (type != typeof(string) && string.IsNullOrEmpty(str))
        {
            str = "\"" + str + "\"";
        }
        return str;
    }
    #endregion

    #region List转换成Json
    /// <summary>
    /// List转换成Json
    /// </summary>
    public static string ListToJson<T>(IList<T> list)
    {
        object obj = list[0];
        return ListToJson<T>(list, obj.GetType().Name);
    }

    /// <summary>
    /// List转换成Json
    /// </summary>
    public static string ListToJson<T>(IList<T> list, string jsonName)
    {
        StringBuilder Json = new StringBuilder();
        if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
        Json.Append("{\"" + jsonName + "\":[");
        if (list.Count > 0)
        {
            for (int i = 0; i < list.Count; i++)
            {
                T obj = Activator.CreateInstance<T>();
                PropertyInfo[] pi = obj.GetType().GetProperties();
                Json.Append("{");
                for (int j = 0; j < pi.Length; j++)
                {
                    Type type = pi[j].GetValue(list[i], null).GetType();
                    Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                    if (j < pi.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < list.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");
        return Json.ToString();
    }
    #endregion

    #region 对象转换为Json
    /// <summary>
    /// 对象转换为Json
    /// </summary>
    /// <param name="jsonObject">对象</param>
    /// <returns>Json字符串</returns>
    public static string ToJson(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() + "‘";
            }
            else if (objectValue is string)
            {
                value = "‘" + ToJson(objectValue.ToString()) + "‘";
            }
            else if (objectValue is IEnumerable)
            {
                value = ToJson((IEnumerable)objectValue);
            }
            else
            {
                value = ToJson(objectValue.ToString());
            }
            jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "}";
    }
    #endregion

    #region 对象集合转换Json
    /// <summary>
    /// 对象集合转换Json
    /// </summary>
    /// <param name="array">集合对象</param>
    /// <returns>Json字符串</returns>
    public static string ToJson(IEnumerable array)
    {
        string jsonString = "[";
        foreach (object item in array)
        {
            jsonString += ToJson(item) + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "]";
    }
    #endregion

    #region 普通集合转换Json
    /// <summary>
    /// 普通集合转换Json
    /// </summary>
    /// <param name="array">集合对象</param>
    /// <returns>Json字符串</returns>
    public static string ToArrayString(IEnumerable array)
    {
        string jsonString = "[";
        foreach (object item in array)
        {
            jsonString = ToJson(item.ToString()) + ",";
        }
        jsonString.Remove(jsonString.Length - 1, jsonString.Length);
        return jsonString + "]";
    }
    #endregion

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

            throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
        }
    }
    #endregion

    #region  DataSet转换为Json
    /// <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 + "}";
    }
    #endregion

    #region DataSet转键值对数组字典
    /// <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;
    }
    #endregion

    #region Datatable转换为Json
    /// <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("]");
        return jsonString.ToString();
    }

    /// <summary>
    /// DataTable转换为Json
    /// </summary>
    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].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();
    }
    #endregion

    #region DataTable转键值对集合
    /// <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;
    }
    #endregion

    #region DataTable转List<T>
    /// <summary>
    /// DataTable转List<T>
    /// </summary>
    /// <typeparam name="T">数据项类型</typeparam>
    /// <param name="dt">DataTable</param>
    /// <returns>List数据集</returns>
    public static List<T> DataTableToList<T>(DataTable dt) where T : new()
    {
        List<T> tList = new List<T>();
        if (dt == null || dt.Rows.Count == 0)
        {
            return tList;
        }
        PropertyInfo[] propertys = typeof(T).GetProperties();   //获取此实体的公共属性
        foreach (DataRow dr in dt.Rows)
        {
            T t = new T();
            foreach (PropertyInfo pi in propertys)
            {
                if (!pi.CanWrite)
                {
                    continue;
                }
                string columnName = pi.Name;
                if (dr.Table.Columns.Contains(columnName))
                {
                    // 判断此属性是否有Setter或columnName值是否为空
                    object value = dr[columnName];
                    if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite)
                    {
                        continue;
                    }

                    #region SetValue
                    try
                    {
                        switch (pi.PropertyType.ToString())
                        {
                            case "System.String":
                                pi.SetValue(t, Convert.ToString(value), null);
                                break;
                            case "System.ToChar":
                                pi.SetValue(t, Convert.ToChar(value), null);
                                break;
                            case "System.Int64":
                                pi.SetValue(t, Convert.ToInt64(value), null);
                                break;
                            case "System.Int32":
                                pi.SetValue(t, Convert.ToInt32(value), null);
                                break;
                            case "System.ToUInt64":
                                pi.SetValue(t, Convert.ToUInt64(value), null);
                                break;
                            case "System.ToUInt32":
                                pi.SetValue(t, Convert.ToUInt32(value), null);
                                break;
                            case "System.DateTime":
                                pi.SetValue(t, Convert.ToDateTime(value), null);
                                break;
                            case "System.Boolean":
                                pi.SetValue(t, Convert.ToBoolean(value), null);
                                break;
                            case "System.Double":
                                pi.SetValue(t, Convert.ToDouble(value), null);
                                break;
                            case "System.Decimal":
                                pi.SetValue(t, Convert.ToDecimal(value), null);
                                break;
                            case "System.Single":
                                pi.SetValue(t, Convert.ToSingle(value), null);
                                break;
                            default:
                                pi.SetValue(t, value, null);
                                break;
                        }
                    }
                    catch
                    {
                        //throw (new Exception(ex.Message));
                    }
                    #endregion
                }
            }
            tList.Add(t);
        }
        return tList;
    }
    #endregion

    #region DataTable转JSON
    /// <summary>
    /// 数据表转JSON
    /// </summary>
    /// <param name="dataTable">数据表</param>
    /// <returns>JSON字符串</returns>
    public static string DataTableToJSON(DataTable dt)
    {
        return ObjectToJSON(DataTableToList(dt));
    }
    #endregion

    #region 泛型集合转DataTable
    /// <summary>
    /// 泛型集合转DataTable
    /// </summary>
    /// <typeparam name="T">集合类型</typeparam>
    /// <param name="entityList">泛型集合</param>
    /// <returns>DataTable</returns>
    public static DataTable ListToDataTable<T>(IList<T> entityList)
    {
        if (entityList == null) return null;
        DataTable dt = CreateTable<T>();
        Type entityType = typeof(T);
        //PropertyInfo[] properties = entityType.GetProperties();
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
        foreach (T item in entityList)
        {
            DataRow row = dt.NewRow();
            foreach (PropertyDescriptor property in properties)
            {
                row[property.Name] = property.GetValue(item);
            }
            dt.Rows.Add(row);
        }

        return dt;
    }

    #endregion

    #region 创建DataTable的结构
    /// <summary>
    /// 创建表结构
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    private static DataTable CreateTable<T>()
    {
        Type entityType = typeof(T);
        //PropertyInfo[] properties = entityType.GetProperties();
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
        //生成DataTable的结构
        DataTable dt = new DataTable();
        foreach (PropertyDescriptor prop in properties)
        {
            dt.Columns.Add(prop.Name);
        }
        return dt;
    }
    #endregion

    #region DataReader转换为Json
    /// <summary>
    /// DataReader转换为Json
    /// </summary>
    /// <param name="dataReader">DataReader对象</param>
    /// <returns>Json字符串</returns>
    public static string ToJson(DbDataReader dataReader)
    {
        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("},");
        }
        dataReader.Close();
        jsonString.Remove(jsonString.Length - 1, 1);
        jsonString.Append("]");
        return jsonString.ToString();
    }
    #endregion

    #region DataReader转实体
    /// <summary>
    /// DataReader转实体
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="dr">DataReader</param>
    /// <returns>实体</returns>
    public static T DataReaderToModel<T>(IDataReader dr) where T : new()
    {
        T t = new T();
        if (dr == null)
        {
            dr.Close();
            return default(T);
        }
        using (dr)
        {
            if (dr.Read())
            {
                PropertyInfo[] propertys = t.GetType().GetProperties(); //获取此实体的公共属性
                List<string> DBFieldNameList = new List<string>(dr.FieldCount);
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    DBFieldNameList.Add(dr.GetName(i).ToLower());
                }

                foreach (PropertyInfo pi in propertys)
                {
                    if (!pi.CanWrite)
                    {
                        continue;
                    }
                    string columnName = pi.Name;
                    if (DBFieldNameList.Contains(columnName.ToLower()))
                    {
                        //判断此属性是否有Setter或columnName值是否为空
                        object value = dr[columnName];
                        if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite)
                        {
                            continue;
                        }

                        #region SetValue
                        try
                        {
                            switch (pi.PropertyType.ToString())
                            {
                                case "System.String":
                                    pi.SetValue(t, Convert.ToString(value), null);
                                    break;
                                case "System.ToChar":
                                    pi.SetValue(t, Convert.ToChar(value), null);
                                    break;
                                case "System.Int64":
                                    pi.SetValue(t, Convert.ToInt64(value), null);
                                    break;
                                case "System.Int32":
                                    pi.SetValue(t, Convert.ToInt32(value), null);
                                    break;
                                case "System.ToUInt64":
                                    pi.SetValue(t, Convert.ToUInt64(value), null);
                                    break;
                                case "System.ToUInt32":
                                    pi.SetValue(t, Convert.ToUInt32(value), null);
                                    break;
                                case "System.DateTime":
                                    pi.SetValue(t, Convert.ToDateTime(value), null);
                                    break;
                                case "System.Boolean":
                                    pi.SetValue(t, Convert.ToBoolean(value), null);
                                    break;
                                case "System.Double":
                                    pi.SetValue(t, Convert.ToDouble(value), null);
                                    break;
                                case "System.Decimal":
                                    pi.SetValue(t, Convert.ToDecimal(value), null);
                                    break;
                                case "System.Single":
                                    pi.SetValue(t, Convert.ToSingle(value), null);
                                    break;
                                default:
                                    pi.SetValue(t, value, null);
                                    break;
                            }
                        }
                        catch
                        {
                            //throw (new Exception(ex.Message));
                        }
                        #endregion
                    }
                }
            }
        }
        dr.Close();
        return t;
    }
    #endregion

    #region DataReader转List<T>
    /// <summary>
    /// DataReader转List<T>
    /// </summary>
    /// <typeparam name="T">数据类型</typeparam>
    /// <param name="dr">DataReader</param>
    /// <returns>List数据集</returns>
    public static List<T> DataReaderToList<T>(IDataReader dr) where T : new()
    {
        List<T> tList = new List<T>();
        if (dr == null)
        {
            dr.Close();
            return tList;
        }
        using (dr)
        {
            PropertyInfo[] propertys = typeof(T).GetProperties();    //获取此实体的公共属性
            List<string> DBFieldNameList = new List<string>(dr.FieldCount);
            for (int i = 0; i < dr.FieldCount; i++)
            {
                DBFieldNameList.Add(dr.GetName(i).ToLower());
            }
            while (dr.Read())
            {
                T t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    if (!pi.CanWrite)
                    {
                        continue;
                    }
                    string columnName = pi.Name;
                    if (DBFieldNameList.Contains(columnName.ToLower()))
                    {
                        // 判断此属性是否有Setter或columnName值是否为空
                        object value = dr[columnName];
                        if (value is DBNull || value == DBNull.Value || value == null || !pi.CanWrite)
                        {
                            continue;
                        }
                        #region SetValue
                        try
                        {
                            switch (pi.PropertyType.ToString())
                            {
                                case "System.String":
                                    pi.SetValue(t, Convert.ToString(value), null);
                                    break;
                                case "System.ToChar":
                                    pi.SetValue(t, Convert.ToChar(value), null);
                                    break;
                                case "System.Int64":
                                    pi.SetValue(t, Convert.ToInt64(value), null);
                                    break;
                                case "System.Int32":
                                    pi.SetValue(t, Convert.ToInt32(value), null);
                                    break;
                                case "System.ToUInt64":
                                    pi.SetValue(t, Convert.ToUInt64(value), null);
                                    break;
                                case "System.ToUInt32":
                                    pi.SetValue(t, Convert.ToUInt32(value), null);
                                    break;
                                case "System.DateTime":
                                    pi.SetValue(t, Convert.ToDateTime(value), null);
                                    break;
                                case "System.Boolean":
                                    pi.SetValue(t, Convert.ToBoolean(value), null);
                                    break;
                                case "System.Double":
                                    pi.SetValue(t, Convert.ToDouble(value), null);
                                    break;
                                case "System.Decimal":
                                    pi.SetValue(t, Convert.ToDecimal(value), null);
                                    break;
                                case "System.Single":
                                    pi.SetValue(t, Convert.ToSingle(value), null);
                                    break;
                                default:
                                    pi.SetValue(t, value, null);
                                    break;
                            }
                        }
                        catch
                        {
                            //throw (new Exception(ex.Message));
                        }
                        #endregion
                    }
                }
                tList.Add(t);
            }
        }
        dr.Close();
        return tList;
    }
    #endregion

    #region 序列化、反序列化
    /// <summary>
    /// 对象序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static String Serialize<T>(T obj)
    {
        String s;
        JavaScriptSerializer ser = new JavaScriptSerializer();
        ser.MaxJsonLength = Int32.MaxValue;
        s = ser.Serialize(obj);
        /*
        DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
        using (MemoryStream ms = new MemoryStream()) {
            ser.WriteObject(ms, obj);
            s = Encoding.Default.GetString(ms.ToArray());
        }
        */
        return s;
    }
    /// <summary>
    /// 反序列化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T Deserialize<T>(String json)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        return jss.Deserialize<T>(json);

        //T o;
        //json = HttpContext.Current.Server.UrlDecode(json);
        //JavaScriptSerializer ser = new JavaScriptSerializer();
        //ser.MaxJsonLength = Int32.MaxValue;
        //o = ser.Deserialize<T>(json);
        //return o;
        /*
        o = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
            o = (T)(ser.ReadObject(ms));
        }
        */

    }
    #endregion

    #region JSON文本转对象,泛型方法
    /// <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
        {
            return jss.Deserialize<T>(jsonText);
        }
        catch (Exception ex)
        {
            throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
        }
    }

    #endregion

    #region 将JSON文本转换为数据表数据
    /// <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);
    }
    #endregion

    #region  将JSON文本转换成数据行
    /// <summary>
    /// 将JSON文本转换成数据行
    /// </summary>
    /// <param name="jsonText">JSON文本</param>
    /// <returns>数据行的字典</returns>
    public static Dictionary<string, object> DataRowFromJSON(string jsonText)
    {
        return JSONToObject<Dictionary<string, object>>(jsonText);
    }
    #endregion
}
时间: 2024-10-05 03:09:38

.net Json JavaScriptSerializer JsonHelper类的相关文章

JavaScriptSerializer的实现-常用JsonHelper类

最近开始自己写自己的项目了,终于鼓起勇气迈出了自己认为的这一大步! 先来通用的helper类和大家分享一下 ,第一个是Object转为json序列的类,这个网上有很多,但我实践了一下大部分都不能用的,或者有各种bug,其实C#中有一个很好的类可以解决这个问题,他就是--JavaScriptSerializer类,有了这个类,只需简单的几行代码,就可以把你的object类型转化成json往前台输出了! 首先我们要在项目中引用 System.Web.Extensions这个dll,才可以使用Java

也谈C#之Json,从Json字符串到类代码

原文:也谈C#之Json,从Json字符串到类代码  阅读目录 json转类对象 逆思考 从json字符串自动生成C#类  json转类对象 自从.net 4.0开始,微软提供了一整套的针对json进行处理的方案.其中,就有如何把json字符串转化成C#类对象,其实这段代码很多人都清楚,大家也都认识,我就不多说,先贴代码. 1.添加引用 System.Web.Extensions 2.测试一下代码 1 static class Program 2 { 3 /// <summary> 4 ///

转换Json格式帮助类

using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Data; using System.Collections; namespace AIMSCommon { /// <summary> /// 转换Json格式帮助类 /// </summary> public class JsonHelper { /// <summ

[C#]JavaScriptSerializer 帮助类

关键代码: using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.Script.Serialization; namespace YanZhiwei.DotNet3._5.Utilities.Common { /// <summary> /// JavaScriptSerializer 帮助类 /// </summary> publ

json 对c++类的序列化(自动生成代码)

[动机] 之前写网络协议的时候,使用的是google protobuf,protobuf不但在性能和扩展性上有很好的优势,protoc自动生成c++类代码的工具,这点确实给程序员带来了很多便利. 做后面一项目使用的json格式来传输,然后就萌生了实现像protoc这样的工具,根据json文件来生成c++类代码,并且生成序列化代码,这样在写网络的时候就无需把jsonvalue序列化散落在各处. [思路] 之前写object-c的时候,如果你要对类的序列化,你必须实现NSCoding协议(接口),

jQuery Ajax 请求报长度过长的错误:Error during serialization or deserialization using the JSON JavaScriptSerializer

{"Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set 在web项目的web.config <configuration>节下增加 <system.web.extensions>    <scripting>    

使用Physics_Body_Editor获得json文件的类

[转自]:http://www.cocoachina.com/bbs/read.php?tid=209290 工具介绍,json文件获得方法,请参考原帖 MyBodyParser.h 1 // 2 // MyBodyParser.h 3 // 4 // Created by Jason Xu. 5 // 6 // 7 8 #pragma once 9 10 #include <string> 11 #include "cocos2d.h" 12 USING_NS_CC; 1

C#自定义将各种对象转换成JSON格式的类

这个C#封装类可以用于将各种格式的数据转换成JSON格式,包括List转换成Json,普通集合转换Json ,DataSet转换为Json ,Datatable转换为Json ,DataReader转换为Json等,如果你需要将对象转换成JSON,可以使用这个类. using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Reflection; using

.net MVC 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错,字符串的长度超过了为 maxJsonLength 属性设置的值

在.net mvc的controller中,方法返回JsonResult,一般我们这么写: [HttpPost] public JsonResult QueryFeature(string url, string whereClause) { string str=""; return Json(str); } 此时如果str过长,就会报“使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错,字符串的长度超过了为 maxJsonLength 属性设置的值