using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;

  

 public  static class JsonCSharpHelp
{
/// <summary>
/// 取得某个Json value
/// </summary>
/// <param name="JsonString">{Name:aaaaa,Value:aaaa}</param>
/// <param name="tagName"></param>
/// <returns></returns>
public static string GetJsonValue(string JsonString,string tagName)
{
JsonString = JsonString.TrimStart('{');
JsonString = JsonString.TrimEnd('}');
string[] splts = JsonString.Split(',');
foreach (string tmp in splts)
{
if (tmp != string.Empty)
{
string[] tag = tmp.Split(':');
if (tag[0] == tagName) return tag[1];
}
}
return string.Empty;
} /// <summary>
/// 获取系统字典里的json对象集合
/// json对象集合格式:[{"key":"1","value":"default"},{"key":"2","value":"default1"},{"key":"3","value":"default2"}]
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="JsonStr"></param>
/// <returns></returns>
public static List<T> JSONStringToList<T>(this string JsonStr)
{ /*JavaScriptSerializer Serializer = new JavaScriptSerializer(); List<T> objs = Serializer.Deserialize<List<T>>(JsonStr); return objs;*/ return JsonConvert.DeserializeObject<List<T>>(JsonStr);
} /// <summary>
/// 把json字符串转成对象
/// </summary>
/// <typeparam name="T">对象</typeparam>
/// <param name="data">json字符串</param>
public static T JSONStringToObj<T>(string data)
{
/* JavaScriptSerializer json = new JavaScriptSerializer();
return json.Deserialize<T>(data);*/ return JsonConvert.DeserializeObject<T>(data);
} /// <summary>
/// 把对象转成json字符串
/// </summary>
/// <param name="o">对象</param>
/// <returns>json字符串</returns>
public static string ObjToJSONString(object o)
{
/*System.Text.StringBuilder sb = new System.Text.StringBuilder();
JavaScriptSerializer json = new JavaScriptSerializer();
json.Serialize(o, sb);
return sb.ToString();*/
// return JsonConvert.SerializeObject(o, new DataTableConverter());
/*var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
var json = JsonConvert.SerializeObject(response, Formatting.Indented, jSetting);*/
return JsonConvert.SerializeObject(o, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-dd hh:mm:ss"});
} /// <summary>
/// 将原表类型为decimal类型的数据改为string类型
/// </summary>
/// <param name="argDataTable"></param>
/// <returns></returns>
public static DataTable ModifyDataTableColumnType(DataTable argDataTable)
{
bool bl = false;
DataTable dtResult = new DataTable();
//克隆表结构
dtResult = argDataTable.Clone();
foreach (DataColumn col in dtResult.Columns)
{
if (col.DataType == typeof(decimal))
{
//修改列类型
col.DataType = typeof(String);
bl = true;
}
}
if (bl)
{
foreach (DataRow row in argDataTable.Rows)
{
DataRow rowNew = dtResult.NewRow();
rowNew.ItemArray = row.ItemArray;
dtResult.Rows.Add(rowNew);
}
return dtResult;
}
return argDataTable;
} /// <summary>
/// 传入jsong串,获取匹配key的value值
/// </summary>
/// <param name="JsonStr"></param>
/// <param name="matchKey"></param>
/// <returns></returns>
public static string GetSysParamValueByKey(string JsonStr, string matchKey)
{
string strResult = "";
IList<SysParamJsonObj> list = JsonCSharpHelp.JSONStringToList<SysParamJsonObj>(JsonStr);
foreach (SysParamJsonObj sysOjb in list)
{
if (sysOjb.key.ToUpper() == matchKey.ToUpper())
{
strResult = sysOjb.value;
break;
}
}
return strResult;
} /// <summary>
///根据对象SysParamJsonObj列表获取到某个key对应的value值
/// </summary>
/// <param name="list"></param>
/// <param name="matchKey"></param>
/// <returns></returns>
public static string GetSysParamValueByKey(IList<SimpleParamObj> list, string matchKey)
{
string strResult = "";
if (list == null) return strResult;
foreach (SimpleParamObj sysOjb in list)
{
if (sysOjb.K.ToUpper() == matchKey.ToUpper())
{
strResult = sysOjb.V;
break;
}
}
return strResult;
} /// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">json对象 "{\"3\":123,body:456,list:{title:'abc',body:'what'}}"</param>
/// <param name="field">属性名称</param>
/// <param name="erro">输出错误信息</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field, out string erro)
{
erro = string.Empty;
if (info == null) return null;
JObject jo = null;
try
{
jo = JObject.Parse(info.ToString());
}
catch (Exception e)
{
erro = "传入对象非json对象格式:" + e.Message;
return null;
} if (jo.Property(field) == null || jo.Property(field).ToString() == "")
{
erro = "键值 " + field + " 不存在!";
return null;
}
return jo.Property(field).Value;
} /// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">json对象 "{\"3\":123,body:456,list:{title:'abc',body:'what'}}"</param>
/// <param name="field">属性名称</param>
/// <param name="erro">输出错误信息</param>
/// <returns></returns>
public static Hashtable GetPropertyValue(object info, string[] fields)
{
Hashtable ht = new Hashtable();
// erro = string.Empty;
if (info == null) return null;
// Type t = info.GetType(); // info = "{\"3\":123,body:456,list:{title:'abc',body:'what'}}";
/* if (t != typeof(JObject))
{
erro = "传入对象非json对象格式";
return null;
}*/
JObject jo = null;
try
{
jo = JObject.Parse(info.ToString());
}
catch (Exception e)
{
// erro = "传入对象非json对象格式:" + e.Message;
return null;
}
int len = fields.Length;
object[] os = new object[len];
IEnumerable<JProperty> properties = jo.Properties();
int i = 0;
bool bl = false;
string f = string.Empty;
for (i = 0; i < len; i++)
{
bl = false;
f = fields[i];
foreach (JProperty item in properties)
{
if (item.Name.ToUpper() == f.ToUpper())
{
ht.Add(f, item.Value);
//os[i] = item.Value;
bl = true;
break;
}
}
if (!bl)
{
ht.Add(f, "");
// erro = "没有找到键值对匹配项" + f;
// return null;
}
} return ht;
} /// <summary>
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
/// </summary>
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;
} /// <summary>
/// 将时间字符串转为Json时间
/// </summary>
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;
} /* /// <summary>
/// JSON序列化
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string pattern = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(pattern);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
/// <summary>
/// JSON反序列化
/// </summary>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T JsonDeserialize<T>(string jsonString)
{
string pattern = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(pattern);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
*/ /// <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("]");
if (jsonString.Length == 1)
{
return "[]";
}
return jsonString.ToString();
} /// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <param name="dataCount">数据总量 分页用</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt, int dataCount)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
jsonString.Append("\"DATA_COUNT\":" + dataCount + ",");
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("]");
if (jsonString.Length == 1)
{
return "[]";
}
return jsonString.ToString();
} /// <summary>
/// DataTable转成Json
/// </summary>
/// <param name="jsonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
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] is DBNull ? string.Empty : 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();
} /// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IDataReader dataReader)
{
try
{
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("},");
}
if (!dataReader.IsClosed)
{
dataReader.Close();
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
if (jsonString.Length == 1)
{
return "[]";
}
return jsonString.ToString();
}
catch (Exception ex)
{
throw ex;
}
} /// <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 + "}";
} /// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string String2Json(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;
case '\v':
sb.Append("\\v"); break;
case '\0':
sb.Append("\\0"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
} /// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private static string StringFormat(string str, Type type)
{
if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
else if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type == typeof(byte[]))
{
str = "\"" + str + "\"";
}
else if (type == typeof(Guid))
{
str = "\"" + str + "\"";
}
return str;
} }

  

    /// <summary>
/// json对象
/// </summary>
[Serializable]
public class SysParamJsonObj
{
/// <summary>
/// id
/// </summary>
public string key; /// <summary>
/// value
/// </summary>
public string value;
}

  

开发日记:JsonCSharpHelp的更多相关文章

  1. 微信小程序开发日记——高仿知乎日报(中)

    本人对知乎日报是情有独钟,看我的博客和github就知道了,写了几个不同技术类型的知乎日报APP要做微信小程序首先要对html,css,js有一定的基础,还有对微信小程序的API也要非常熟悉 我将该教 ...

  2. 微信小程序开发日记——高仿知乎日报(上)

    本人对知乎日报是情有独钟,看我的博客和github就知道了,写了几个不同技术类型的知乎日报APP 要做微信小程序首先要对html,css,js有一定的基础,还有对微信小程序的API也要非常熟悉 我将该 ...

  3. 嵌入式Linux驱动开发日记

    嵌入式Linux驱动开发日记 主机硬件环境 开发机:虚拟机Ubuntu12.04 内存: 1G 硬盘:80GB 目标板硬件环境 CPU: SP5V210 (开发板:QT210) SDRAM: 512M ...

  4. 【原创】shadowebdict开发日记:基于linux的简明英汉字典(四)

    全系列目录: [原创]shadowebdict开发日记:基于linux的简明英汉字典(一) [原创]shadowebdict开发日记:基于linux的简明英汉字典(二) [原创]shadowebdic ...

  5. 【原创】shadowebdict开发日记:基于linux的简明英汉字典(三)

    全系列目录: [原创]shadowebdict开发日记:基于linux的简明英汉字典(一) [原创]shadowebdict开发日记:基于linux的简明英汉字典(二) [原创]shadowebdic ...

  6. 【原创】shadowebdict开发日记:基于linux的简明英汉字典(二)

    全系列目录: [原创]shadowebdict开发日记:基于linux的简明英汉字典(一) [原创]shadowebdict开发日记:基于linux的简明英汉字典(二) [原创]shadowebdic ...

  7. 【原创】shadowebdict开发日记:基于linux的简明英汉字典(一)

    全系列目录: [原创]shadowebdict开发日记:基于linux的简明英汉字典(一) [原创]shadowebdict开发日记:基于linux的简明英汉字典(二) [原创]shadowebdic ...

  8. LayIM.AspNetCore Middleware 开发日记(一)闲言碎语

    前言 前几天写博客的时候突然看见了历史上的今天.不禁感慨时光如梭,这系列博客后来被我标注了已经过时,但是还有很多小伙伴咨询我.既然过时就要更新,正好 .NET Core 也出来很久了,于是乎想到把La ...

  9. 【Android开发日记】之入门篇(七)——Android数据存储(上)

    在讲解Android的数据源组件——ContentProvider之前我觉得很有必要先弄清楚Android的数据结构. 数据和程序是应用构成的两个核心要素,数据存储永远是应用开发中最重要的主题之一,也 ...

随机推荐

  1. 为什么有那么多人愿意喝"鸡汤"?

    什么是心灵鸡汤 心灵鸡汤,就是“充满知识与感情的话语”,柔软.温暖,充满正能量.心灵鸡汤是一种安慰剂,可以怡情,作阅读快餐:亦可移情,挫折.抑郁时,疗效直逼“打鸡血”.这也是“心灵鸡汤”风靡不衰的原因 ...

  2. 百度地图DEMO-路线导航,测距,标点

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  3. Asp.Net Core 轻松学-一行代码搞定文件上传

    前言     在 Web 应用程序开发过程中,总是无法避免涉及到文件上传,这次我们来聊一聊怎么去实现一个简单方便可复用文件上传功能:通过创建自定义绑定模型来实现文件上传. 1. 实现自定义绑定模型 1 ...

  4. python 题库1

    1. 生成一个1到50的大字符串,每个数字之间有个空格,例如1 2 3 4 ……50 解题思路: (1)声明一个空字符串变量用于保存生成的字符串 (2)使用for循环+range()函数生成一个1到5 ...

  5. Raptor入门与安装

    作为计算机导论的一部分,Raptor的图形化界面可以让编程的初学者更加容易深入理解算法,可以作为一个简单入门的学习工具. 1.Raptor是什么? Raptor( the Rapid Algorith ...

  6. 在表单提交之前做校验-利用jQuery的submit方法

    点击表单中的提交按钮,默认就会提交表单,如果要在表单提交之前做一些校验,那么就可以用jQuery的submit方法. 也就是jQuery的submit的方法执行顺序,在表单的提交之前.用法如下: $( ...

  7. 小程序中使用ECharts 异步加载数据

    官网例子都是同步的,怎么引入及同步demo请移步官网 <view class="container"> <ec-canvas id="mychart-d ...

  8. 微信h5 video的问题

    https://blog.csdn.net/hf123lsk/article/details/78920211

  9. win10 64位IIS链接32位ACCESS数据库

    window10中IIS运行.asp文件链接数据库时出现错误,显示“An error occurred on the server when processing the URL. Please co ...

  10. selenium+python自动化测试系列---基础知识篇(1、HTML基础知识1)

    1.什么是HTML HTML是一种描述网页的语言.HTML指超文本标记语言(Hyper Text Markup Language),它不是一种编程语言,而是一种标记语言(markup language ...