using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using BP.DA;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace BP.Tools
{
public class Json
{
public static DataTable ConvertToDataTable(JArray dataArr)
{
if (dataArr == null || dataArr.Count <= 0)
return null;
DataTable result = new DataTable();
foreach (var row in dataArr)
{
foreach (var jToken in row)
{
var jproperty = jToken as JProperty;
if (jproperty == null) continue;
if (result.Columns[jproperty.Name] == null)
result.Columns.Add(jproperty.Name, typeof(string));
}
}
foreach (var row in dataArr)
{
var datarow = result.NewRow();
foreach (var jToken in row)
{
var jProperty = jToken as JProperty;
if (jProperty == null)
continue;
datarow[jProperty.Name] = jProperty.Value.ToString();
}
result.Rows.Add(datarow);
}
return result;
}
///
/// 把一个json转化一个datatable
///
/// 一个json字符串
/// 序列化的datatable
public static DataTable ToDataTable(string strJson)
{
if (strJson.Trim().IndexOf('[') != 0)
{
strJson = "[" + strJson + "]";
}
strJson = strJson.Replace("\\\\\"", "'");
DataTable dtt = (DataTable)JsonConvert.DeserializeObject(strJson);
return dtt;
}
///
/// 把一个json转化一个datatable 杨玉慧
///
/// 一个json字符串
/// 序列化的datatable
public static DataTable ToDataTableOneRow(string strJson)
{
////杨玉慧 写 用这个写
if (strJson.Trim().IndexOf('[') != 0)
{
strJson = "[" + strJson + "]";
}
DataTable dtt = (DataTable)JsonConvert.DeserializeObject(strJson);
return dtt;
}
///
/// 把dataset转成json 不区分大小写.
///
///
///
public static string DataSetToJson(DataSet dataSet, bool isUpperColumn = true)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
if (isUpperColumn == true)
jsonString += "\"" + table.TableName + "\":" + DataTableToJson(table, true) + ",";
else
jsonString += "\"" + table.TableName + "\":" + DataTableToJson(table, false) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
///
/// Datatable转换为Json
///
/// Datatable对象
/// Json字符串
public static string DataTableToJson(DataTable dt, bool isUpperColumn = true)
{
StringBuilder jsonString = new StringBuilder();
if (dt.Rows.Count == 0)
{
jsonString.Append("[]");
return jsonString.ToString();
}
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 = null;
if (isUpperColumn == true)
{
strKey = dt.Columns[j].ColumnName;
}
else
{
strKey = dt.Columns[j].ColumnName;
}
Type type = dt.Columns[j].DataType;
string strValue = "";
if (type == typeof(Single))
{
object v = drc[i][j];
if (v == null || v == DBNull.Value)
{
strValue = "0";
}
else
{
//double f =(double)((float)v);
strValue = ((float)v).ToString("0." + new string('#', 339));
}
//strValue = v == null ? "0" : v;
//strValue = drc[i][j] == null ? "" : ((float)(drc[i][j])).ToString("0.00");
}
else
{
strValue = drc[i][j] == null ? "" : drc[i][j].ToString();
}
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();
}
///
/// 格式化字符型、日期型、布尔型
///
///
///
///
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + Convert.ToDateTime(str).ToShortDateString() + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
if (str.Length == 0)
str = "\"\"";
return str;
}
///
/// 过滤特殊字符
///
///
///
private static string String2Json(String s)
{
System.Text.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();
}
///
/// 把一个json转化一个datatable
///
/// 一个json字符串
/// 序列化的datatable
public static DataSet ToDataSet(string json)
{
////杨玉慧 写 用这个写
DataSet ds = JsonConvert.DeserializeObject(json);
return ds;
}
///
/// 对象转换为Json字符串
///
/// 对象
/// Json字符串
public static string ToJson(object jsonObject)
{
string json = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
return json;
}
///
/// 对象集合转换Json
///
/// 集合对象
/// Json字符串
public static string ToJson(IEnumerable array)
{
string jsonStr = JsonConvert.SerializeObject(array);
return jsonStr;
}
///
/// 普通集合转换Json
///
/// 集合对象
/// Json字符串
public static string ToArrayString(IEnumerable array)
{
string jsonStr = JsonConvert.SerializeObject(array);
return jsonStr;
}
///
/// 删除结尾字符
///
/// 需要删除的字符
/// 完成后的字符串
private static string DeleteLast(string str)
{
if (str.Length > 1)
{
return str.Substring(0, str.Length - 1);
}
return str;
}
///
/// 把Ht转换成Entity模式.
///
///
///
public static string ToJsonEntityModel(Hashtable ht)
{
string strs = "{";
foreach (string key in ht.Keys)
{
var val = ht[key];
if (val == null)
{
strs += "\"" + key + "\":\"\",";
continue;
}
var tp = val.GetType();
if (tp == typeof(int)
|| tp == typeof(float)
|| tp == typeof(decimal)
|| tp == typeof(double)
|| tp == typeof(Int64))
{
strs += "\"" + key + "\":" + ht[key] + ",";
}
else
{
string valText = ht[key].ToString().Replace("\"", "\\\\\"");
strs += "\"" + key + "\":\"" + valText + "\",";
}
}
strs += "\"EndJSON\":\"0\"";
strs += "}";
strs = TranJsonStr(strs);
return strs;
}
public static string ToJsonEntitiesNoNameMode(Hashtable ht)
{
DataTable dt = new DataTable();
dt.Columns.Add("No");
dt.Columns.Add("Name");
foreach (string key in ht.Keys)
{
DataRow dr = dt.NewRow();
dr["No"] = key;
dr["Name"] = ht[key];
dt.Rows.Add(dr);
}
return BP.Tools.Json.DataTableToJson(dt, false);
}
///
/// 转化成Json.
///
/// Hashtable
/// 是否编号名称格式
///
public static string ToJson(Hashtable ht)
{
return ToJsonEntityModel(ht);
}
///
/// Datatable转换为Json
///
/// Datatable对象
/// Json字符串
public static string ToJson(DataTable table)
{
// 旧版本...
return JsonConvert.SerializeObject(table);
}
///
/// DataSet转换为Json
///
/// DataSet对象
/// Json字符串
public static string ToJson(DataSet dataSet)
{
return JsonConvert.SerializeObject(dataSet);
}
///
/// String转换为Json
///
/// String对象
/// Json字符串
public static string ToJson(string value)
{
if (DataType.IsNullOrEmpty(value))
return string.Empty;
string temstr;
temstr = value;
temstr = temstr.Replace("{", "{").Replace("}", "}").Replace(":", ":").Replace(",", ",").Replace("[", "【").Replace("]", "】").Replace(";", ";").Replace("\n", "
").Replace("\r", "");
temstr = temstr.Replace("\t", " ");
temstr = temstr.Replace("'", "\'");
temstr = temstr.Replace(@"\", @"\\");
temstr = temstr.Replace("\"", "\"\"");
return temstr;
}
///
/// JSON字符串的转义
///
///
///
private static string TranJsonStr(string jsonStr)
{
string strs = jsonStr;
strs = strs.Replace("\\", "\\\\");
strs = strs.Replace("\n", "\\n");
strs = strs.Replace("\b", "\\b");
strs = strs.Replace("\t", "\\t");
strs = strs.Replace("\f", "\\f");
strs = strs.Replace("\r", "\\r");
strs = strs.Replace("/", "\\/");
return strs;
}
}
public static partial class ExtensionsJson
{
///
/// 字串反序列化成linq对象
///
/// 字串
///
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
}
///
/// 字串反序列化成指定对象实体(列表)
///
/// 实体类型
/// 字串
///
public static List ToList(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject>(Json);
}
}
}