using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Web.Script.Serialization; namespace HNWD.Pregrant.Common { public static class JsonHelper { public static string Serialize(Object o, string str2) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); Serializer.MaxJsonLength = Int32.MaxValue; string str = Serializer.Serialize(o); return str; } public static string Serialize(Object o) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); Serializer.MaxJsonLength = Int32.MaxValue; string str = Serializer.Serialize(o); return str; } public static string SerializeWithSuffix(Object o, string Suffix = ",OK!") { JavaScriptSerializer Serializer = new JavaScriptSerializer(); Serializer.MaxJsonLength = int.MaxValue; string str = Serializer.Serialize(o); return str + Suffix; } public static string Serialize(DataSet o) { string str = JsonConvert.SerializeObject(o, new DataTableConverter()); str = str.Replace("Table", "dataList"); return str; } public static string Serialize(DataTable table, string type = "javascript") { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List> parentRow = new List>(); Dictionary childRow; foreach (DataRow row in table.Rows) { childRow = new Dictionary(); foreach (DataColumn col in table.Columns) { childRow.Add(col.ColumnName, row[col]); } parentRow.Add(childRow); } return jsSerializer.Serialize(parentRow); } public static string Serialize(DataTable table, string type = "net", string type2 = "net") { string jsonString = JsonConvert.SerializeObject(table); return jsonString; } public static string Serialize(DataTable table, string type = "string", string type2 = "string", string type3 = "string") { var jsonString = new StringBuilder(); jsonString.Append("{\"" + table.TableName + "\":"); if (table.Rows.Count > 0) { jsonString.Append("["); for (int i = 0; i < table.Rows.Count; i++) { jsonString.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { if (j < table.Columns.Count - 1) { jsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\","); } else if (j == table.Columns.Count - 1) { jsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\""); } } if (i == table.Rows.Count - 1) { jsonString.Append("}"); } else { jsonString.Append("},"); } } jsonString.Append("]"); jsonString.Append("}"); } return jsonString.ToString(); } public static T Deserialize(string json) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); T objs = Serializer.Deserialize(json); return objs; } public static T DeserializeWithSuffix(string json, string Suffix = ",OK!") { json = json.Replace(Suffix, ""); JavaScriptSerializer Serializer = new JavaScriptSerializer(); T objs = Serializer.Deserialize(json); return objs; } } }