/*------------------------------------------------------------------
-- COPYRIGHT (C) 2011-2020 hanhe
-- ALL RIGHTS RESERVED.
-- han he
-- CREATE DATE: 2014/06/27
-- CREATE MAN: 姜新军
-- 对象与JSON字符串互相转化类
-- MODIFY HISTORY:
-- MODIFY DATE:
-- MODIFY MAN:
-- MODIFY DESC:
-- MODIFY DATE:
-- MODIFY MAN:
-- MODIFY DESC:
---------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.Reflection;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;///记得引用这个命名空间
namespace HH.WMS.Common
{
///
/// json类库
///
public class JsonHelper
{
///
/// 实例化
///
public JsonHelper()
{
}
#region 把DataTable数据,转化成JSON字符串
///
/// 把DataTable数据,转化成JSON字符串
///
/// 对象名称
/// DataTable数据集
/// JSON数组字符串
public static string DataTableToJson(string jsonName, DataTable dt, int total)
{
StringBuilder Json = new StringBuilder();
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("{\"" + jsonName + "\":[");
}
else
{
if (total > 0)
{
Json.Append("[");
}
}
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++)
{
string key = dt.Columns[j].ColumnName.ToString();
string value = dt.Rows[i][j].ToString().Trim();
//DateTime dts = DateTime.Now;
if (Util.IsTDateTime(value))
{
value = DateTime.Parse(value).ToString("yyyy-MM-dd");
}
Json.Append("\"" + key + "\":\"" + value.Replace("\"","”") + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("],");
Json.Append("\"total\":" + total + "");
Json.Append("}");
}
else
{
if (total > 0)
{
Json.Append("]");
}
}
return Json.ToString();
}
///
/// 把DataTable数据,转化成JSON字符串
///
/// 对象名称
/// DataTable数据集
/// 总页数
/// 总记录数
/// JSON数组字符串
public static string DataTableToJson(string jsonName, DataTable dt, int pageCount, int totalRecord)
{
StringBuilder Json = new StringBuilder();
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("{\"" + jsonName + "\":[");
}
else
{
if (totalRecord > 0)
{
Json.Append("[");
}
}
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++)
{
string key = dt.Columns[j].ColumnName.ToString();
string value = dt.Rows[i][j].ToString().Trim();
//DateTime dts = DateTime.Now;
if (Util.IsTDateTime(value))
{
value = DateTime.Parse(value).ToString("yyyy-MM-dd");
}
Json.Append("\"" + key + "\":\"" + value + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("],");
Json.Append("\"total\":" + totalRecord + ",\"pagecount\":" + pageCount + "");
Json.Append("}");
}
else
{
if (totalRecord > 0)
{
Json.Append("]");
}
}
return Json.ToString();
}
#endregion
#region 把JSON字符串转化为DataTable
///
/// Json 字符串 转换为 DataTable数据集合
///
///
///
public static DataTable JsonToDataTable(string jsonString)
{
DataTable dataTable = new DataTable(); //实例化
try
{
ArrayList arrayList = JsonConvert.DeserializeObject(jsonString);
if (arrayList.Count > 0)
{
foreach (Dictionary dictionary in arrayList)
{
if (dictionary.Keys.Count() == 0)
{
return dataTable;
}
//Columns
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
//Rows
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch
{
}
return dataTable;
}
#endregion
#region 把LIST数据对象,转化成JSON数组字符串
///
/// 把LIST数据对象,转化成JSON数组字符串
///
/// 对象集合
/// JSON名称
/// JSON数组字符串
public static string IListToJson(string jsonName, IList IL, long totalRows)
{
StringBuilder Json = new StringBuilder();
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("{\"" + jsonName + "\":[");
}
else
{
Json.Append("[");
}
if (IL.Count > 0)
{
for (int i = 0; i < IL.Count; i++)
{
T obj = Activator.CreateInstance();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
object value = pis[j].GetValue(IL[i], null);
//处理日期类型
if (Util.IsTDateTime(value))
{
//格式化日期
value = Util.ToString(Convert.ToDateTime(value), "yyyy-MM-dd HH:mm:ss");
//格式化成JSON日期。
string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(pattern);
value = reg.Replace(value.ToString(), matchEvaluator);
}
Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + value + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < IL.Count - 1)
{
Json.Append(",");
}
}
}
if (!string.IsNullOrEmpty(jsonName))
{
if (totalRows >= 0)
{
Json.Append("],\"total\":\"" + totalRows + "\"}");
}
else
{
Json.Append("]}");
}
}
else
{
Json.Append("]");
}
return Json.ToString();
}
///
/// 把LIST数据对象,转化成JSON数组字符串
///
/// 对象集合
/// JSON名称
/// 总记录数
/// 总页数
/// JSON数组字符串
public static string IListToJson(string jsonName, IList IL, long totalRows, long pageCount)
{
StringBuilder Json = new StringBuilder();
if (!string.IsNullOrEmpty(jsonName))
{
Json.Append("{\"" + jsonName + "\":[");
}
else
{
Json.Append("[");
}
if (IL.Count > 0)
{
for (int i = 0; i < IL.Count; i++)
{
T obj = Activator.CreateInstance();
Type type = obj.GetType();
PropertyInfo[] pis = type.GetProperties();
Json.Append("{");
for (int j = 0; j < pis.Length; j++)
{
object value = pis[j].GetValue(IL[i], null);
//处理日期类型
if (Util.IsTDateTime(value))
{
//格式化日期
value = Util.ToString(Convert.ToDateTime(value), "yyyy-MM-dd HH:mm:ss");
//格式化成JSON日期。
string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(pattern);
value = reg.Replace(value.ToString(), matchEvaluator);
}
Json.Append("\"" + pis[j].Name.ToString() + "\":\"" + value + "\"");
if (j < pis.Length - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < IL.Count - 1)
{
Json.Append(",");
}
}
}
if (!string.IsNullOrEmpty(jsonName))
{
if (totalRows >= 0)
{
Json.Append("],\"total\":\"" + totalRows + "\",\"pagecount\":\"" + pageCount + "\"}");
}
else
{
Json.Append("]}");
}
}
else
{
Json.Append("]");
}
return Json.ToString();
}
#endregion
#region 把对象序列化 JSON 字符串
///
/// 把对象序列化 JSON 字符串
///
/// 对象类型
/// 对象实体
/// JSON字符串
public static string GetJson(T obj)
{
//记住 添加引用 System.ServiceModel.Web
/**
* 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
* */
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
json.WriteObject(ms, obj);
string szJson = Encoding.UTF8.GetString(ms.ToArray());
return szJson;
}
}
#endregion
#region 把JSON字符串还原为对象
///
/// 把JSON字符串还原为对象
///
/// 对象类型
/// JSON字符串
/// 对象实体
public static T ParseFormJson(string szJson)
{
T obj = Activator.CreateInstance();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
return (T)dcj.ReadObject(ms);
}
}
#endregion
#region 将JSON字符串转换成对象集合
///
/// 将JSON字符串转换成对象集合
///
///
///
///
public static List JSONStringToList(string JsonStr)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
Serializer.MaxJsonLength = Int32.MaxValue;
List objs = Serializer.Deserialize>(JsonStr);
return objs;
}
#endregion
#region 将Model对象转换成JsonString
public static string ModelToJsonString(T model)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize(model);
}
#endregion
#region 将json字符串转换为DataTable
///
/// 将json转换为DataTable
///
/// 得到的json
/// 返回datatable
/// [HanHe(ZMM)] CREATED 2017/10/12
public static DataTable JsonToDT(string strJson)
{
try
{
if (string.IsNullOrEmpty(strJson))
{
return null;
}
//转换json格式
strJson = strJson.Replace(",\"", "$$$\"").Replace("\":", "\"&&&").ToString();
//取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = "test";// rg.Match(strJson).Value;
DataTable tb = null;
if (strJson.IndexOf("[") > -1)
{
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
}
if (strJson.IndexOf("]") > -1)
{
strJson = strJson.Substring(0, strJson.IndexOf("]"));
}
//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
//string[] strRows = strRow.Split('*');
string[] strRows = strRow.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);
//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
var dc = new DataColumn();
//string[] strCell = str.Split('#');
string[] strCell = str.Split(new string[] { "&&&" }, StringSplitOptions.RemoveEmptyEntries);
if (strCell[0].Substring(0, 1) == "\"")
{
int a = strCell[0].Length;
dc.ColumnName = strCell[0].Substring(1, a - 2);
}
else
{
dc.ColumnName = strCell[0];
}
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}
//增加内容
DataRow dr = tb.NewRow();
for (int r = 0; r < strRows.Length; r++)
{
//dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
dr[r] = strRows[r].Split(new string[] { "&&&" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
}
tb.Rows.Add(dr);
tb.AcceptChanges();
}
return tb;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
///
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
///
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;
}
///
/// 将时间字符串转为Json时间
///
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;
}
///
/// 将时间字符串转为Json时间
///
private static string ConvertDateStringToJsonDate(string DateTime)
{
string result = string.Empty;
DateTime dt = Convert.ToDateTime(DateTime);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - Convert.ToDateTime("1970-01-01");
result = string.Format("/Date({0}+0800)/", ts.TotalMilliseconds);
return result;
}
///
/// 是否为日期+时间型字符串
///
///
///
public static bool IsTDateTime(string StrSource)
{
return Regex.IsMatch(StrSource, @"^(((((1[6-9]|[2-9]d)d{2})-(0?|1)-(0?[1-9]|d|3))|(((1[6-9]|[2-9]d)d{2})-(0?|1)-(0?[1-9]|d|30))|(((1[6-9]|[2-9]d)d{2})-0?2-(0?[1-9]|1d|2[0-8]))|(((1[6-9]|[2-9]d)(0||)|((16||)00))-0?2-29-)) (20|21|22|23|[0-1]?d):[0-5]?d:[0-5]?d)$ ");
}
///
/// Convert a List{T} to a DataTable.
///
public static DataTable ToDataTable(List items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
///
/// Determine of specified type is nullable
///
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
///
/// Return underlying type if type is Nullable otherwise return the type
///
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
public static string GetValue(string name)
{
try
{
var jsonFile = System.AppDomain.CurrentDomain.BaseDirectory + "\\Config.json";
using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o = (JObject)JToken.ReadFrom(reader);
var value = o[name].ToString();
return value.Replace("\r\n", "");
}
}
}
catch (Exception ex)
{
Log.Detail("获取json文件", "值timeSpan失败!原因:" + ex.Message);
return "";
}
}
}
}