You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

223 lines
7.4 KiB
C#

11 months ago
using System;
using System.Data;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Collections;
using Newtonsoft.Json.Converters;
namespace DSWeb.TruckMng.Helper
{
public class JsonConvert
{
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
var jsonObj = json;
if (json == null)
jsonObj = string.Empty;
obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonObj);
return obj;
}
public static string Serialize<T>(T obj)
{
string retVal = string.Empty;
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
//这里使用自定义日期格式如果不使用的话默认是ISO8601格式
timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
//jsonObject是准备转换的对象
retVal = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, timeConverter);
return retVal;
}
#region 转化Dataset or DataTable
#region 直接转为Json字符串
public static string DataTableToJSON(DataTable dt, string dtName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
jw.WritePropertyName(dtName);
jw.WriteStartArray();
foreach (DataRow dr in dt.Rows)
{
jw.WriteStartObject();
foreach (DataColumn dc in dt.Columns)
{
jw.WritePropertyName(dc.ColumnName);
ser.Serialize(jw, dr[dc].ToString());
}
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
sw.Close();
jw.Close();
}
return sb.ToString();
}
#endregion
#region 转化为Controller中可以使用Json(new {..})使用的方式
#region 例子
//public static Dictionary<string, object> getTable()
//{
// string sql = "select user_name, active_indicator, create_date from users";
// string connString = "database=db; server=localhost; user id=sa;";
// return JsonMethods.ToJson(GetDataTable(sql, connString));
//}
//private static DataTable GetDataTable(string sql, string connString)
//{
// using (SqlConnection myConnection = new SqlConnection(connString))
// {
// using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
// {
// myConnection.Open();
// using (SqlDataReader myReader = myCommand.ExecuteReader())
// {
// DataTable myTable = new DataTable();
// myTable.TableName = "mydt";
// myTable.Load(myReader);
// myConnection.Close();
// return myTable;
// }
// }
// }
//}
//Controller中 return Json(new {data=getTable().ToArray()});
#endregion
private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
{
List<Dictionary<string, object>> objs =
new List<Dictionary<string, object>>();
if (table == null)
return objs;
foreach (DataRow dr in table.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
for (int i = 0; i < table.Columns.Count; i++)
{
drow.Add(table.Columns[i].ColumnName, dr[i]);
}
objs.Add(drow);
}
return objs;
}
/// <summary>
/// 把DataTable转化为Controller可以转为Json数据的数据集合
/// </summary>
/// <param name="table">需要转换的DataTable</param>
/// <returns></returns>
public static List<Dictionary<string, object>> ToJson(DataTable table)
{
return RowsToDictionary(table);
}
//public static Dictionary<string, object> ToJson(DataTable table)
//{
// Dictionary<string, object> dict = new Dictionary<string, object>();
// dict.Add(table.TableName, RowsToDictionary(table));
// return dict;
//}
/// <summary>
/// 把DataSet转化为Controller可以转为Json数据的数据集合
/// </summary>
/// <param name="data">需要转换的DataSet</param>
/// <returns></returns>
public static Dictionary<string, object> ToJson(DataSet data)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable table in data.Tables)
{
dict.Add(table.TableName, RowsToDictionary(table));
}
return dict;
}
#endregion
#endregion
static public object JsonGetValue(string jsondata,string jsonname)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(jsondata);
object value;
if (!json.TryGetValue(jsonname, out value))
{
throw new Exception("数据中不存在此值!");
}
return value;
}
/// <summary>
/// 获取JsonString
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
public static string GetJsonString(DataSet ds)
{
string res = ""; ;
IList<Hashtable> mList = new List<Hashtable>();
try {
foreach (DataRow row in ds.Tables[0].Rows)
{
Hashtable ht = new Hashtable();
foreach (DataColumn col in ds.Tables[0].Columns)
{
ht.Add(col.ColumnName, row[col.ColumnName]);
}
mList.Add(ht);
}
res = Newtonsoft.Json.JsonConvert.SerializeObject(mList);
}
catch (Exception ee)
{
string error = ee.Message;
}
return res;
}
}
}
//public class CustomerJsonConverter : JsonConverter
//{
// public override void WriteJson(JsonWriter writer, object value)
// {
// throw new NotImplementedException();
// }
// public override object ReadJson(JsonReader reader, Type objectType)
// {
// throw new NotImplementedException();
// }
// public override bool CanConvert(Type objectType)
// {
// return true;
// }
//}