Error[8]: Undefined offset: 4, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

概述四个主要 *** 作类:JsonConverter、JsonHelper、JsonSplit、AjaxResult一、JsonConverter:自定义查询对象转换动态类、object动态类转换json包、json转换object动态类、DataReader转换为Json、DataSet转换为Json、Da

四个主要 *** 作类:JsonConverter 、JsonHelper 、JsonSplit 、AJAXResult

一、JsonConverter:

自定义查询对象转换动态类、object动态类转换Json包、Json转换object动态类、DataReader转换为Json、DataSet转换为Json、Datatable转成Json、Datatable转换为Json 、格式化字符型日期型布尔型、过滤特殊字符等

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.linq;using System.Web.Script.Serialization;using System.Collections;namespace Common{  public class JsonConverter  {        /// <summary>    /// 自定义查询对象转换动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj"></param>    /// <returns></returns>    public static dynamic JsonClass(object obj)     {      return ConvertJson(Serialize(obj,true));    }    /// <summary>    /// object动态类转换Json包    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj">对象</param>    /// <param name="DateConvert">时间戳是否转换成日期类型</param>    /// <returns></returns>    public static string Serialize(object obj,bool DateConvert = false)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      var str = Jss.Serialize(obj);      if (DateConvert)      {        str = System.Text.RegularExpressions.Regex.Replace(str,@"\/Date\((\d+)\)\/",match =>        {          DateTime dt = new DateTime(1970,1,1);          dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));          dt = dt.TolocalTime();          return dt.ToString("yyyy-MM-dd HH:mm:ss");        });      }      return str;    }    /// <summary>    /// Json转换object动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="Json"></param>    /// <returns></returns>    public static dynamic ConvertJson(string Json)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      Jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });      dynamic dy = Jss.Deserialize(Json,typeof(object)) as dynamic;      return dy;    }    /// <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      /// add yuangang by 2015-05-19    /// </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>     /// Datatable转成Json      /// add yuangang by 2015-05-19    /// </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>      /// Datatable转换为Json      /// add yuangang by 2015-05-19    /// </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>     /// 格式化字符型、日期型、布尔型     /// add yuangang by 2015-05-19    /// </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>     /// 过滤特殊字符     /// add yuangang by 2015-05-19    /// </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 '
using System.Collections.Generic;using System.Text;using Newtonsoft.Json;using System.Runtime.Serialization.Json;using System.IO;namespace Common{  /// <summary>  /// 提供了一个关于Json的辅助类  /// </summary>  public class JsonHelper  {    #region Method    /// <summary>    /// 类对像转换成Json格式    /// </summary>     /// <returns></returns>    public static string ToJson(object t)    {     return JsonConvert.SerializeObject(t,Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });    }    /// <summary>    /// 类对像转换成Json格式    /// </summary>    /// <param name="t"></param>    /// <param name="HasNullignore">是否忽略NulL值</param>    /// <returns></returns>    public static string ToJson(object t,bool HasNullignore)    {      if (HasNullignore)        return JsonConvert.SerializeObject(t,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });      else        return ToJson(t);    }    /// <summary>    /// Json格式转换    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strjson"></param>    /// <returns></returns>    public static T FromJson<T>(string strjson) where T : class    {      if (!strjson.IsNullOrEmpty())        return JsonConvert.DeserializeObject<T>(strjson);      return null;    }    /// <summary>    /// 功能描述:将List转换为Json    /// </summary>    /// <param name="a"></param>    /// <returns></returns>    public static string ListToJson(IList<object> a)    {      DataContractJsonSerializer Json = new DataContractJsonSerializer(a.GetType());      string szJson = "";      //序列化      using (MemoryStream stream = new MemoryStream())      {        Json.WriteObject(stream,a);        szJson = EnCoding.UTF8.GetString(stream.ToArray());      }      return szJson;    }    #endregion    #region Property    /// <summary>    /// 数据状态    /// </summary>    public string Status { get; set; }    /// <summary>    /// 提示信息    /// </summary>    public string Msg { get; set; }    /// <summary>    /// 回传URL    /// </summary>    public string ReUrl { get; set; }    /// <summary>    /// 数据包    /// </summary>    public object Data { get; set; }    #endregion  }}
': sb.Append("\0"); break; default: sb.Append(c); break; } } return sb.ToString(); } public static string GetDataGrIDJsonByDataSet(DataSet ds,string totalProperty,string root) { return GetDataGrIDJsonByDatatable(ds.tables[0],totalProperty,root); } public static string GetDataGrIDJsonByDatatable(Datatable dt,string root) { StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("({\"" + totalProperty + "\":\"" + dt.Rows.Count + "\","); JsonBuilder.Append("\""); JsonBuilder.Append(root); JsonBuilder.Append("\":["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\""); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\":\""); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\","); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("},"); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); JsonBuilder.Append("})"); return JsonBuilder.ToString(); } public static string GetTreeJsonByDataSet(DataSet ds) { return GetTreeJsonByDatatable(ds.tables[0]); } public static string GetTreeJsonByDatatable(Datatable datatable) { Datatable dt = FormatDatatableForTree(datatable); StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\'"); if (dt.Columns[j].Columnname == "leaf") { string leafValue = dt.Rows[i][j].ToString(); if (!string.IsNullOrEmpty(leafValue)) { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Remove(JsonBuilder.Length - 1,1); } } else if (dt.Columns[j].Columnname == "customUrl") { JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append(":\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); return JsonBuilder.ToString(); } private static Datatable FormatDatatableForTree(Datatable dt) { Datatable dtTree = new Datatable(); dtTree.Columns.Add("ID",typeof(string)); dtTree.Columns.Add("text",typeof(string)); dtTree.Columns.Add("leaf",typeof(string)); dtTree.Columns.Add("cls",typeof(string)); dtTree.Columns.Add("customUrl",typeof(string)); dtTree.AcceptChanges(); for (int i = 0; i < dt.Rows.Count; i++) { DaTarow drTree = dtTree.NewRow(); drTree["ID"] = dt.Rows[i]["ID"].ToString(); drTree["text"] = dt.Rows[i]["text"].ToString(); if (dt.Rows[i]["leaf"].ToString() == "Y") { drTree["leaf"] = "true"; drTree["cls"] = "file"; } else { drTree["cls"] = "folder"; } drTree["customUrl"] = dt.Rows[i]["customUrl"].ToString(); dtTree.Rows.Add(drTree); } return dtTree; } } /// <summary> /// 动态JsON解析 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonObject : System.Dynamic.DynamicObject { private IDictionary<string,object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string,object> dictionary) { this.Dictionary = dictionary; } public overrIDe bool TryGetMember(System.Dynamic.GetMemberBinder binder,out object result) { result = this.Dictionary[binder.name]; if (result is IDictionary<string,object>) { result = new DynamicJsonObject(result as IDictionary<string,object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string,object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string,object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.name); } } /// <summary> /// 动态JsON转换 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonConverter : JavaScriptConverter { public overrIDe object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public overrIDe IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer) { throw new NotImplementedException(); } public overrIDe IEnumerable<Type> SupportedTypes { get { return new System.Collections.ObjectModel.ReadonlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } }}

二、JsonHelper:Json的辅助

using System;using System.Collections.Generic;using System.linq;using System.Web;namespace Common{  /// <summary>  /// 判断字符串是否为JsON  /// </summary>  public class JsonSplit  {    private static bool IsJsonStart(ref string Json)    {      if (!string.IsNullOrEmpty(Json))      {        Json = Json.Trim('\r','\n',' ');        if (Json.Length > 1)        {          char s = Json[0];          char e = Json[Json.Length - 1];          return (s == '{' && e == '}') || (s == '[' && e == ']');        }      }      return false;    }    public static bool IsJson(string Json)    {      int errIndex;      return IsJson(Json,out errIndex);    }    public static bool IsJson(string Json,out int errIndex)    {      errIndex = 0;      if (IsJsonStart(ref Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (SetCharState(c,ref cs) && cs.childrenStart)//设置关键符号状态。          {            string item = Json.Substring(i);            int err;            int length = GetValueLength(item,true,out err);            cs.childrenStart = false;            if (err > 0)            {              errIndex = i + err;              return false;            }            i = i + length - 1;          }          if (cs.isError)          {            errIndex = i;            return false;          }        }        return !cs.arrayStart && !cs.JsonStart;      }      return false;    }    /// <summary>    /// 获取值的长度(当Json值嵌套以"{"或"["开头时)    /// </summary>    private static int GetValueLength(string Json,bool breakOnErr,out int errIndex)    {      errIndex = 0;      int len = 0;      if (!string.IsNullOrEmpty(Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (!SetCharState(c,ref cs))//设置关键符号状态。          {            if (!cs.JsonStart && !cs.arrayStart)//Json结束,又不是数组,则退出。            {              break;            }          }          else if (cs.childrenStart)//正常字符,值状态下。          {            int length = GetValueLength(Json.Substring(i),breakOnErr,out errIndex);//递归子值,返回一个长度。。。            cs.childrenStart = false;            cs.valueStart = 0;            //cs.state = 0;            i = i + length - 1;          }          if (breakOnErr && cs.isError)          {            errIndex = i;            return i;          }          if (!cs.JsonStart && !cs.arrayStart)//记录当前结束位置。          {            len = i + 1;//长度比索引+1            break;          }        }      }      return len;    }    /// <summary>    /// 字符状态    /// </summary>    private class CharState    {      internal bool JsonStart = false;//以 "{"开始了...      internal bool setDicValue = false;// 可以设置字典值了。      internal bool escapeChar = false;//以"\"转义符号开始了      /// <summary>      /// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。      /// </summary>      internal bool arrayStart = false;//以"[" 符号开始了      internal bool childrenStart = false;//子级嵌套开始了。      /// <summary>      /// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】      /// </summary>      internal int state = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int keyStart = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int valueStart = 0;      internal bool isError = false;//是否语法错误。      internal voID CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)      {        if (keyStart > 1 || valueStart > 1)        {          return;        }        //示例 ["aa",{"bbbb":123,"fff","ddd"}]         switch (c)        {          case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]            isError = JsonStart && state == 0;//重复开始错误 同时不是值处理。            break;          case '}':            isError = !JsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}            break;          case '[':            isError = arrayStart && state == 0;//重复开始错误            break;          case ']':            isError = !arrayStart || JsonStart;//重复开始错误 或者 Json 未结束            break;          case '"':          case '\'':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              //重复开始 [""",{"" "}]              isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);            }            if (!isError && arrayStart && !JsonStart && c == '\'')//['aa',{}]            {              isError = true;            }            break;          case ':':            isError = !JsonStart || state == 1;//重复出现。            break;          case ',':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              if (JsonStart)              {                isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。              }              else if (arrayStart)//["aa,] [,] [{},{}]              {                isError = keyStart == 0 && !setDicValue;              }            }            break;          case ' ':          case '\r':          case '\n'://[ "a",\r\n{} ]          case '
using System.Web.Script.Serialization;namespace Common{  /// <summary>  /// 前台AJAX请求的统一返回结果类  /// </summary>  public class AJAXResult  {    private AJAXResult()    {    }    private bool iserror = false;    /// <summary>    /// 是否产生错误    /// </summary>    public bool IsError { get { return iserror; } }    /// <summary>    /// 错误信息,或者成功信息    /// </summary>    public string Message { get; set; }    /// <summary>    /// 成功可能时返回的数据    /// </summary>    public object Data { get; set; }    #region Error    public static AJAXResult Error()    {      return new AJAXResult()      {        iserror = true      };    }    public static AJAXResult Error(string message)    {      return new AJAXResult()      {        iserror = true,Message = message      };    }    #endregion    #region Success    public static AJAXResult Success()    {      return new AJAXResult()      {        iserror = false      };    }    public static AJAXResult Success(string message)    {      return new AJAXResult()      {        iserror = false,Message = message      };    }    public static AJAXResult Success(object data)    {      return new AJAXResult()      {        iserror = false,Data = data      };    }    public static AJAXResult Success(object data,string message)    {      return new AJAXResult()      {        iserror = false,Data = data,Message = message      };    }    #endregion    /// <summary>    /// 序列化    /// </summary>    /// <returns></returns>    public overrIDe string ToString()    {      return new JavaScriptSerializer().Serialize(this);    }  }}
': case '\t': break; default: //值开头。。 isError = (!JsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);// break; } //if (isError) //{ //} } } /// <summary> /// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理) /// </summary> private static bool SetCharState(char c,ref CharState cs) { cs.CheckIsError(c); switch (c) { case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] #region 大括号 if (cs.keyStart <= 0 && cs.valueStart <= 0) { cs.keyStart = 0; cs.valueStart = 0; if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; } else { cs.state = 0; } cs.JsonStart = true;//开始。 return true; } #endregion break; case '}': #region 大括号结束 if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.JsonStart) { cs.JsonStart = false;//正常结束。 cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; cs.setDicValue = true; return true; } // cs.isError = !cs.JsonStart && cs.state == 0; #endregion break; case '[': #region 中括号开始 if (!cs.JsonStart) { cs.arrayStart = true; return true; } else if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; return true; } #endregion break; case ']': #region 中括号结束 if (cs.arrayStart && !cs.JsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。 { cs.keyStart = 0; cs.valueStart = 0; cs.arrayStart = false; return true; } #endregion break; case '"': case '\'': #region 引号 if (cs.JsonStart || cs.arrayStart) { if (cs.state == 0)//key阶段,有可能是数组["aa",{}] { if (cs.keyStart <= 0) { cs.keyStart = (c == '"' ? 3 : 2); return true; } else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.keyStart = -1; return true; } else { cs.escapeChar = false; } } } else if (cs.state == 1 && cs.JsonStart)//值阶段必须是Json开始了。 { if (cs.valueStart <= 0) { cs.valueStart = (c == '"' ? 3 : 2); return true; } else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.valueStart = -1; return true; } else { cs.escapeChar = false; } } } } #endregion break; case ':': #region 冒号 if (cs.JsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0) { if (cs.keyStart == 1) { cs.keyStart = -1; } cs.state = 1; return true; } // cs.isError = !cs.JsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1); #endregion break; case ',': #region 逗号 //["aa",{aa:12,}] if (cs.JsonStart) { if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1) { cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; //if (cs.valueStart == 1) //{ // cs.valueStart = 0; //} cs.setDicValue = true; return true; } } else if (cs.arrayStart && cs.keyStart <= 2) { cs.keyStart = 0; //if (cs.keyStart == 1) //{ // cs.keyStart = -1; //} return true; } #endregion break; case ' ': case '\r': case '\n'://[ "a",\r\n{} ] case '[+++]': case '\t': if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.JsonStart && { return true;//跳过空格。 } break; default: //值开头。。 if (c == '\') //转义符号 { if (cs.escapeChar) { cs.escapeChar = false; } else { cs.escapeChar = true; return true; } } else { cs.escapeChar = false; } if (cs.JsonStart || cs.arrayStart) // Json 或数组开始了。 { if (cs.keyStart <= 0 && cs.state == 0) { cs.keyStart = 1;//无引号的 } else if (cs.valueStart <= 0 && cs.state == 1 && cs.JsonStart)//只有Json开始才有值。 { cs.valueStart = 1;//无引号的 } } break; } return false; } }}

三、JsonSplit:判断字符串是否为Json

[+++]

四、AJAXResult:前台AJAX请求的统一返回结果类

[+++]

常用的一些Json *** 作类,留着备用,需要的朋友的直接拿去用吧。

总结

以上是内存溢出为你收集整理的C# JsonHelper *** 作辅助类,拿来直接用全部内容,希望文章能够帮你解决C# JsonHelper *** 作辅助类,拿来直接用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 165, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 5, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

概述四个主要 *** 作类:JsonConverter、JsonHelper、JsonSplit、AjaxResult一、JsonConverter:自定义查询对象转换动态类、object动态类转换json包、json转换object动态类、DataReader转换为Json、DataSet转换为Json、Da

四个主要 *** 作类:JsonConverter 、JsonHelper 、JsonSplit 、AJAXResult

一、JsonConverter:

自定义查询对象转换动态类、object动态类转换Json包、Json转换object动态类、DataReader转换为Json、DataSet转换为Json、Datatable转成Json、Datatable转换为Json 、格式化字符型日期型布尔型、过滤特殊字符等

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.linq;using System.Web.Script.Serialization;using System.Collections;namespace Common{  public class JsonConverter  {        /// <summary>    /// 自定义查询对象转换动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj"></param>    /// <returns></returns>    public static dynamic JsonClass(object obj)     {      return ConvertJson(Serialize(obj,true));    }    /// <summary>    /// object动态类转换Json包    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj">对象</param>    /// <param name="DateConvert">时间戳是否转换成日期类型</param>    /// <returns></returns>    public static string Serialize(object obj,bool DateConvert = false)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      var str = Jss.Serialize(obj);      if (DateConvert)      {        str = System.Text.RegularExpressions.Regex.Replace(str,@"\/Date\((\d+)\)\/",match =>        {          DateTime dt = new DateTime(1970,1,1);          dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));          dt = dt.TolocalTime();          return dt.ToString("yyyy-MM-dd HH:mm:ss");        });      }      return str;    }    /// <summary>    /// Json转换object动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="Json"></param>    /// <returns></returns>    public static dynamic ConvertJson(string Json)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      Jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });      dynamic dy = Jss.Deserialize(Json,typeof(object)) as dynamic;      return dy;    }    /// <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      /// add yuangang by 2015-05-19    /// </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>     /// Datatable转成Json      /// add yuangang by 2015-05-19    /// </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>      /// Datatable转换为Json      /// add yuangang by 2015-05-19    /// </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>     /// 格式化字符型、日期型、布尔型     /// add yuangang by 2015-05-19    /// </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>     /// 过滤特殊字符     /// add yuangang by 2015-05-19    /// </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 '
using System.Collections.Generic;using System.Text;using Newtonsoft.Json;using System.Runtime.Serialization.Json;using System.IO;namespace Common{  /// <summary>  /// 提供了一个关于Json的辅助类  /// </summary>  public class JsonHelper  {    #region Method    /// <summary>    /// 类对像转换成Json格式    /// </summary>     /// <returns></returns>    public static string ToJson(object t)    {     return JsonConvert.SerializeObject(t,Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });    }    /// <summary>    /// 类对像转换成Json格式    /// </summary>    /// <param name="t"></param>    /// <param name="HasNullignore">是否忽略NulL值</param>    /// <returns></returns>    public static string ToJson(object t,bool HasNullignore)    {      if (HasNullignore)        return JsonConvert.SerializeObject(t,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });      else        return ToJson(t);    }    /// <summary>    /// Json格式转换    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strjson"></param>    /// <returns></returns>    public static T FromJson<T>(string strjson) where T : class    {      if (!strjson.IsNullOrEmpty())        return JsonConvert.DeserializeObject<T>(strjson);      return null;    }    /// <summary>    /// 功能描述:将List转换为Json    /// </summary>    /// <param name="a"></param>    /// <returns></returns>    public static string ListToJson(IList<object> a)    {      DataContractJsonSerializer Json = new DataContractJsonSerializer(a.GetType());      string szJson = "";      //序列化      using (MemoryStream stream = new MemoryStream())      {        Json.WriteObject(stream,a);        szJson = EnCoding.UTF8.GetString(stream.ToArray());      }      return szJson;    }    #endregion    #region Property    /// <summary>    /// 数据状态    /// </summary>    public string Status { get; set; }    /// <summary>    /// 提示信息    /// </summary>    public string Msg { get; set; }    /// <summary>    /// 回传URL    /// </summary>    public string ReUrl { get; set; }    /// <summary>    /// 数据包    /// </summary>    public object Data { get; set; }    #endregion  }}
': sb.Append("\0"); break; default: sb.Append(c); break; } } return sb.ToString(); } public static string GetDataGrIDJsonByDataSet(DataSet ds,string totalProperty,string root) { return GetDataGrIDJsonByDatatable(ds.tables[0],totalProperty,root); } public static string GetDataGrIDJsonByDatatable(Datatable dt,string root) { StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("({\"" + totalProperty + "\":\"" + dt.Rows.Count + "\","); JsonBuilder.Append("\""); JsonBuilder.Append(root); JsonBuilder.Append("\":["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\""); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\":\""); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\","); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("},"); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); JsonBuilder.Append("})"); return JsonBuilder.ToString(); } public static string GetTreeJsonByDataSet(DataSet ds) { return GetTreeJsonByDatatable(ds.tables[0]); } public static string GetTreeJsonByDatatable(Datatable datatable) { Datatable dt = FormatDatatableForTree(datatable); StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\'"); if (dt.Columns[j].Columnname == "leaf") { string leafValue = dt.Rows[i][j].ToString(); if (!string.IsNullOrEmpty(leafValue)) { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Remove(JsonBuilder.Length - 1,1); } } else if (dt.Columns[j].Columnname == "customUrl") { JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append(":\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); return JsonBuilder.ToString(); } private static Datatable FormatDatatableForTree(Datatable dt) { Datatable dtTree = new Datatable(); dtTree.Columns.Add("ID",typeof(string)); dtTree.Columns.Add("text",typeof(string)); dtTree.Columns.Add("leaf",typeof(string)); dtTree.Columns.Add("cls",typeof(string)); dtTree.Columns.Add("customUrl",typeof(string)); dtTree.AcceptChanges(); for (int i = 0; i < dt.Rows.Count; i++) { DaTarow drTree = dtTree.NewRow(); drTree["ID"] = dt.Rows[i]["ID"].ToString(); drTree["text"] = dt.Rows[i]["text"].ToString(); if (dt.Rows[i]["leaf"].ToString() == "Y") { drTree["leaf"] = "true"; drTree["cls"] = "file"; } else { drTree["cls"] = "folder"; } drTree["customUrl"] = dt.Rows[i]["customUrl"].ToString(); dtTree.Rows.Add(drTree); } return dtTree; } } /// <summary> /// 动态JsON解析 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonObject : System.Dynamic.DynamicObject { private IDictionary<string,object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string,object> dictionary) { this.Dictionary = dictionary; } public overrIDe bool TryGetMember(System.Dynamic.GetMemberBinder binder,out object result) { result = this.Dictionary[binder.name]; if (result is IDictionary<string,object>) { result = new DynamicJsonObject(result as IDictionary<string,object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string,object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string,object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.name); } } /// <summary> /// 动态JsON转换 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonConverter : JavaScriptConverter { public overrIDe object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public overrIDe IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer) { throw new NotImplementedException(); } public overrIDe IEnumerable<Type> SupportedTypes { get { return new System.Collections.ObjectModel.ReadonlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } }}

二、JsonHelper:Json的辅助

using System;using System.Collections.Generic;using System.linq;using System.Web;namespace Common{  /// <summary>  /// 判断字符串是否为JsON  /// </summary>  public class JsonSplit  {    private static bool IsJsonStart(ref string Json)    {      if (!string.IsNullOrEmpty(Json))      {        Json = Json.Trim('\r','\n',' ');        if (Json.Length > 1)        {          char s = Json[0];          char e = Json[Json.Length - 1];          return (s == '{' && e == '}') || (s == '[' && e == ']');        }      }      return false;    }    public static bool IsJson(string Json)    {      int errIndex;      return IsJson(Json,out errIndex);    }    public static bool IsJson(string Json,out int errIndex)    {      errIndex = 0;      if (IsJsonStart(ref Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (SetCharState(c,ref cs) && cs.childrenStart)//设置关键符号状态。          {            string item = Json.Substring(i);            int err;            int length = GetValueLength(item,true,out err);            cs.childrenStart = false;            if (err > 0)            {              errIndex = i + err;              return false;            }            i = i + length - 1;          }          if (cs.isError)          {            errIndex = i;            return false;          }        }        return !cs.arrayStart && !cs.JsonStart;      }      return false;    }    /// <summary>    /// 获取值的长度(当Json值嵌套以"{"或"["开头时)    /// </summary>    private static int GetValueLength(string Json,bool breakOnErr,out int errIndex)    {      errIndex = 0;      int len = 0;      if (!string.IsNullOrEmpty(Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (!SetCharState(c,ref cs))//设置关键符号状态。          {            if (!cs.JsonStart && !cs.arrayStart)//Json结束,又不是数组,则退出。            {              break;            }          }          else if (cs.childrenStart)//正常字符,值状态下。          {            int length = GetValueLength(Json.Substring(i),breakOnErr,out errIndex);//递归子值,返回一个长度。。。            cs.childrenStart = false;            cs.valueStart = 0;            //cs.state = 0;            i = i + length - 1;          }          if (breakOnErr && cs.isError)          {            errIndex = i;            return i;          }          if (!cs.JsonStart && !cs.arrayStart)//记录当前结束位置。          {            len = i + 1;//长度比索引+1            break;          }        }      }      return len;    }    /// <summary>    /// 字符状态    /// </summary>    private class CharState    {      internal bool JsonStart = false;//以 "{"开始了...      internal bool setDicValue = false;// 可以设置字典值了。      internal bool escapeChar = false;//以"\"转义符号开始了      /// <summary>      /// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。      /// </summary>      internal bool arrayStart = false;//以"[" 符号开始了      internal bool childrenStart = false;//子级嵌套开始了。      /// <summary>      /// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】      /// </summary>      internal int state = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int keyStart = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int valueStart = 0;      internal bool isError = false;//是否语法错误。      internal voID CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)      {        if (keyStart > 1 || valueStart > 1)        {          return;        }        //示例 ["aa",{"bbbb":123,"fff","ddd"}]         switch (c)        {          case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]            isError = JsonStart && state == 0;//重复开始错误 同时不是值处理。            break;          case '}':            isError = !JsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}            break;          case '[':            isError = arrayStart && state == 0;//重复开始错误            break;          case ']':            isError = !arrayStart || JsonStart;//重复开始错误 或者 Json 未结束            break;          case '"':          case '\'':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              //重复开始 [""",{"" "}]              isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);            }            if (!isError && arrayStart && !JsonStart && c == '\'')//['aa',{}]            {              isError = true;            }            break;          case ':':            isError = !JsonStart || state == 1;//重复出现。            break;          case ',':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              if (JsonStart)              {                isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。              }              else if (arrayStart)//["aa,] [,] [{},{}]              {                isError = keyStart == 0 && !setDicValue;              }            }            break;          case ' ':          case '\r':          case '\n'://[ "a",\r\n{} ]          case '
using System.Web.Script.Serialization;namespace Common{  /// <summary>  /// 前台AJAX请求的统一返回结果类  /// </summary>  public class AJAXResult  {    private AJAXResult()    {    }    private bool iserror = false;    /// <summary>    /// 是否产生错误    /// </summary>    public bool IsError { get { return iserror; } }    /// <summary>    /// 错误信息,或者成功信息    /// </summary>    public string Message { get; set; }    /// <summary>    /// 成功可能时返回的数据    /// </summary>    public object Data { get; set; }    #region Error    public static AJAXResult Error()    {      return new AJAXResult()      {        iserror = true      };    }    public static AJAXResult Error(string message)    {      return new AJAXResult()      {        iserror = true,Message = message      };    }    #endregion    #region Success    public static AJAXResult Success()    {      return new AJAXResult()      {        iserror = false      };    }    public static AJAXResult Success(string message)    {      return new AJAXResult()      {        iserror = false,Message = message      };    }    public static AJAXResult Success(object data)    {      return new AJAXResult()      {        iserror = false,Data = data      };    }    public static AJAXResult Success(object data,string message)    {      return new AJAXResult()      {        iserror = false,Data = data,Message = message      };    }    #endregion    /// <summary>    /// 序列化    /// </summary>    /// <returns></returns>    public overrIDe string ToString()    {      return new JavaScriptSerializer().Serialize(this);    }  }}
': case '\t': break; default: //值开头。。 isError = (!JsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);// break; } //if (isError) //{ //} } } /// <summary> /// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理) /// </summary> private static bool SetCharState(char c,ref CharState cs) { cs.CheckIsError(c); switch (c) { case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] #region 大括号 if (cs.keyStart <= 0 && cs.valueStart <= 0) { cs.keyStart = 0; cs.valueStart = 0; if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; } else { cs.state = 0; } cs.JsonStart = true;//开始。 return true; } #endregion break; case '}': #region 大括号结束 if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.JsonStart) { cs.JsonStart = false;//正常结束。 cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; cs.setDicValue = true; return true; } // cs.isError = !cs.JsonStart && cs.state == 0; #endregion break; case '[': #region 中括号开始 if (!cs.JsonStart) { cs.arrayStart = true; return true; } else if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; return true; } #endregion break; case ']': #region 中括号结束 if (cs.arrayStart && !cs.JsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。 { cs.keyStart = 0; cs.valueStart = 0; cs.arrayStart = false; return true; } #endregion break; case '"': case '\'': #region 引号 if (cs.JsonStart || cs.arrayStart) { if (cs.state == 0)//key阶段,有可能是数组["aa",{}] { if (cs.keyStart <= 0) { cs.keyStart = (c == '"' ? 3 : 2); return true; } else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.keyStart = -1; return true; } else { cs.escapeChar = false; } } } else if (cs.state == 1 && cs.JsonStart)//值阶段必须是Json开始了。 { if (cs.valueStart <= 0) { cs.valueStart = (c == '"' ? 3 : 2); return true; } else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.valueStart = -1; return true; } else { cs.escapeChar = false; } } } } #endregion break; case ':': #region 冒号 if (cs.JsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0) { if (cs.keyStart == 1) { cs.keyStart = -1; } cs.state = 1; return true; } // cs.isError = !cs.JsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1); #endregion break; case ',': #region 逗号 //["aa",{aa:12,}] if (cs.JsonStart) { if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1) { cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; //if (cs.valueStart == 1) //{ // cs.valueStart = 0; //} cs.setDicValue = true; return true; } } else if (cs.arrayStart && cs.keyStart <= 2) { cs.keyStart = 0; //if (cs.keyStart == 1) //{ // cs.keyStart = -1; //} return true; } #endregion break; case ' ': case '\r': case '\n'://[ "a",\r\n{} ] case '': case '\t': if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.JsonStart && { return true;//跳过空格。 } break; default: //值开头。。 if (c == '\') //转义符号 { if (cs.escapeChar) { cs.escapeChar = false; } else { cs.escapeChar = true; return true; } } else { cs.escapeChar = false; } if (cs.JsonStart || cs.arrayStart) // Json 或数组开始了。 { if (cs.keyStart <= 0 && cs.state == 0) { cs.keyStart = 1;//无引号的 } else if (cs.valueStart <= 0 && cs.state == 1 && cs.JsonStart)//只有Json开始才有值。 { cs.valueStart = 1;//无引号的 } } break; } return false; } }}

三、JsonSplit:判断字符串是否为Json

[+++]

四、AJAXResult:前台AJAX请求的统一返回结果类

[+++]

常用的一些Json *** 作类,留着备用,需要的朋友的直接拿去用吧。

总结

以上是内存溢出为你收集整理的C# JsonHelper *** 作辅助类,拿来直接用全部内容,希望文章能够帮你解决C# JsonHelper *** 作辅助类,拿来直接用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 165, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Error[8]: Undefined offset: 6, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

概述四个主要 *** 作类:JsonConverter、JsonHelper、JsonSplit、AjaxResult一、JsonConverter:自定义查询对象转换动态类、object动态类转换json包、json转换object动态类、DataReader转换为Json、DataSet转换为Json、Da

四个主要 *** 作类:JsonConverter 、JsonHelper 、JsonSplit 、AJAXResult

一、JsonConverter:

自定义查询对象转换动态类、object动态类转换Json包、Json转换object动态类、DataReader转换为Json、DataSet转换为Json、Datatable转成Json、Datatable转换为Json 、格式化字符型日期型布尔型、过滤特殊字符等

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.linq;using System.Web.Script.Serialization;using System.Collections;namespace Common{  public class JsonConverter  {        /// <summary>    /// 自定义查询对象转换动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj"></param>    /// <returns></returns>    public static dynamic JsonClass(object obj)     {      return ConvertJson(Serialize(obj,true));    }    /// <summary>    /// object动态类转换Json包    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj">对象</param>    /// <param name="DateConvert">时间戳是否转换成日期类型</param>    /// <returns></returns>    public static string Serialize(object obj,bool DateConvert = false)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      var str = Jss.Serialize(obj);      if (DateConvert)      {        str = System.Text.RegularExpressions.Regex.Replace(str,@"\/Date\((\d+)\)\/",match =>        {          DateTime dt = new DateTime(1970,1,1);          dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));          dt = dt.TolocalTime();          return dt.ToString("yyyy-MM-dd HH:mm:ss");        });      }      return str;    }    /// <summary>    /// Json转换object动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="Json"></param>    /// <returns></returns>    public static dynamic ConvertJson(string Json)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      Jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });      dynamic dy = Jss.Deserialize(Json,typeof(object)) as dynamic;      return dy;    }    /// <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      /// add yuangang by 2015-05-19    /// </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>     /// Datatable转成Json      /// add yuangang by 2015-05-19    /// </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>      /// Datatable转换为Json      /// add yuangang by 2015-05-19    /// </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>     /// 格式化字符型、日期型、布尔型     /// add yuangang by 2015-05-19    /// </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>     /// 过滤特殊字符     /// add yuangang by 2015-05-19    /// </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 '
using System.Collections.Generic;using System.Text;using Newtonsoft.Json;using System.Runtime.Serialization.Json;using System.IO;namespace Common{  /// <summary>  /// 提供了一个关于Json的辅助类  /// </summary>  public class JsonHelper  {    #region Method    /// <summary>    /// 类对像转换成Json格式    /// </summary>     /// <returns></returns>    public static string ToJson(object t)    {     return JsonConvert.SerializeObject(t,Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });    }    /// <summary>    /// 类对像转换成Json格式    /// </summary>    /// <param name="t"></param>    /// <param name="HasNullignore">是否忽略NulL值</param>    /// <returns></returns>    public static string ToJson(object t,bool HasNullignore)    {      if (HasNullignore)        return JsonConvert.SerializeObject(t,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });      else        return ToJson(t);    }    /// <summary>    /// Json格式转换    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strjson"></param>    /// <returns></returns>    public static T FromJson<T>(string strjson) where T : class    {      if (!strjson.IsNullOrEmpty())        return JsonConvert.DeserializeObject<T>(strjson);      return null;    }    /// <summary>    /// 功能描述:将List转换为Json    /// </summary>    /// <param name="a"></param>    /// <returns></returns>    public static string ListToJson(IList<object> a)    {      DataContractJsonSerializer Json = new DataContractJsonSerializer(a.GetType());      string szJson = "";      //序列化      using (MemoryStream stream = new MemoryStream())      {        Json.WriteObject(stream,a);        szJson = EnCoding.UTF8.GetString(stream.ToArray());      }      return szJson;    }    #endregion    #region Property    /// <summary>    /// 数据状态    /// </summary>    public string Status { get; set; }    /// <summary>    /// 提示信息    /// </summary>    public string Msg { get; set; }    /// <summary>    /// 回传URL    /// </summary>    public string ReUrl { get; set; }    /// <summary>    /// 数据包    /// </summary>    public object Data { get; set; }    #endregion  }}
': sb.Append("\0"); break; default: sb.Append(c); break; } } return sb.ToString(); } public static string GetDataGrIDJsonByDataSet(DataSet ds,string totalProperty,string root) { return GetDataGrIDJsonByDatatable(ds.tables[0],totalProperty,root); } public static string GetDataGrIDJsonByDatatable(Datatable dt,string root) { StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("({\"" + totalProperty + "\":\"" + dt.Rows.Count + "\","); JsonBuilder.Append("\""); JsonBuilder.Append(root); JsonBuilder.Append("\":["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\""); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\":\""); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\","); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("},"); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); JsonBuilder.Append("})"); return JsonBuilder.ToString(); } public static string GetTreeJsonByDataSet(DataSet ds) { return GetTreeJsonByDatatable(ds.tables[0]); } public static string GetTreeJsonByDatatable(Datatable datatable) { Datatable dt = FormatDatatableForTree(datatable); StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\'"); if (dt.Columns[j].Columnname == "leaf") { string leafValue = dt.Rows[i][j].ToString(); if (!string.IsNullOrEmpty(leafValue)) { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Remove(JsonBuilder.Length - 1,1); } } else if (dt.Columns[j].Columnname == "customUrl") { JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append(":\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); return JsonBuilder.ToString(); } private static Datatable FormatDatatableForTree(Datatable dt) { Datatable dtTree = new Datatable(); dtTree.Columns.Add("ID",typeof(string)); dtTree.Columns.Add("text",typeof(string)); dtTree.Columns.Add("leaf",typeof(string)); dtTree.Columns.Add("cls",typeof(string)); dtTree.Columns.Add("customUrl",typeof(string)); dtTree.AcceptChanges(); for (int i = 0; i < dt.Rows.Count; i++) { DaTarow drTree = dtTree.NewRow(); drTree["ID"] = dt.Rows[i]["ID"].ToString(); drTree["text"] = dt.Rows[i]["text"].ToString(); if (dt.Rows[i]["leaf"].ToString() == "Y") { drTree["leaf"] = "true"; drTree["cls"] = "file"; } else { drTree["cls"] = "folder"; } drTree["customUrl"] = dt.Rows[i]["customUrl"].ToString(); dtTree.Rows.Add(drTree); } return dtTree; } } /// <summary> /// 动态JsON解析 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonObject : System.Dynamic.DynamicObject { private IDictionary<string,object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string,object> dictionary) { this.Dictionary = dictionary; } public overrIDe bool TryGetMember(System.Dynamic.GetMemberBinder binder,out object result) { result = this.Dictionary[binder.name]; if (result is IDictionary<string,object>) { result = new DynamicJsonObject(result as IDictionary<string,object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string,object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string,object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.name); } } /// <summary> /// 动态JsON转换 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonConverter : JavaScriptConverter { public overrIDe object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public overrIDe IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer) { throw new NotImplementedException(); } public overrIDe IEnumerable<Type> SupportedTypes { get { return new System.Collections.ObjectModel.ReadonlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } }}

二、JsonHelper:Json的辅助

using System;using System.Collections.Generic;using System.linq;using System.Web;namespace Common{  /// <summary>  /// 判断字符串是否为JsON  /// </summary>  public class JsonSplit  {    private static bool IsJsonStart(ref string Json)    {      if (!string.IsNullOrEmpty(Json))      {        Json = Json.Trim('\r','\n',' ');        if (Json.Length > 1)        {          char s = Json[0];          char e = Json[Json.Length - 1];          return (s == '{' && e == '}') || (s == '[' && e == ']');        }      }      return false;    }    public static bool IsJson(string Json)    {      int errIndex;      return IsJson(Json,out errIndex);    }    public static bool IsJson(string Json,out int errIndex)    {      errIndex = 0;      if (IsJsonStart(ref Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (SetCharState(c,ref cs) && cs.childrenStart)//设置关键符号状态。          {            string item = Json.Substring(i);            int err;            int length = GetValueLength(item,true,out err);            cs.childrenStart = false;            if (err > 0)            {              errIndex = i + err;              return false;            }            i = i + length - 1;          }          if (cs.isError)          {            errIndex = i;            return false;          }        }        return !cs.arrayStart && !cs.JsonStart;      }      return false;    }    /// <summary>    /// 获取值的长度(当Json值嵌套以"{"或"["开头时)    /// </summary>    private static int GetValueLength(string Json,bool breakOnErr,out int errIndex)    {      errIndex = 0;      int len = 0;      if (!string.IsNullOrEmpty(Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (!SetCharState(c,ref cs))//设置关键符号状态。          {            if (!cs.JsonStart && !cs.arrayStart)//Json结束,又不是数组,则退出。            {              break;            }          }          else if (cs.childrenStart)//正常字符,值状态下。          {            int length = GetValueLength(Json.Substring(i),breakOnErr,out errIndex);//递归子值,返回一个长度。。。            cs.childrenStart = false;            cs.valueStart = 0;            //cs.state = 0;            i = i + length - 1;          }          if (breakOnErr && cs.isError)          {            errIndex = i;            return i;          }          if (!cs.JsonStart && !cs.arrayStart)//记录当前结束位置。          {            len = i + 1;//长度比索引+1            break;          }        }      }      return len;    }    /// <summary>    /// 字符状态    /// </summary>    private class CharState    {      internal bool JsonStart = false;//以 "{"开始了...      internal bool setDicValue = false;// 可以设置字典值了。      internal bool escapeChar = false;//以"\"转义符号开始了      /// <summary>      /// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。      /// </summary>      internal bool arrayStart = false;//以"[" 符号开始了      internal bool childrenStart = false;//子级嵌套开始了。      /// <summary>      /// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】      /// </summary>      internal int state = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int keyStart = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int valueStart = 0;      internal bool isError = false;//是否语法错误。      internal voID CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)      {        if (keyStart > 1 || valueStart > 1)        {          return;        }        //示例 ["aa",{"bbbb":123,"fff","ddd"}]         switch (c)        {          case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]            isError = JsonStart && state == 0;//重复开始错误 同时不是值处理。            break;          case '}':            isError = !JsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}            break;          case '[':            isError = arrayStart && state == 0;//重复开始错误            break;          case ']':            isError = !arrayStart || JsonStart;//重复开始错误 或者 Json 未结束            break;          case '"':          case '\'':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              //重复开始 [""",{"" "}]              isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);            }            if (!isError && arrayStart && !JsonStart && c == '\'')//['aa',{}]            {              isError = true;            }            break;          case ':':            isError = !JsonStart || state == 1;//重复出现。            break;          case ',':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              if (JsonStart)              {                isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。              }              else if (arrayStart)//["aa,] [,] [{},{}]              {                isError = keyStart == 0 && !setDicValue;              }            }            break;          case ' ':          case '\r':          case '\n'://[ "a",\r\n{} ]          case '
using System.Web.Script.Serialization;namespace Common{  /// <summary>  /// 前台AJAX请求的统一返回结果类  /// </summary>  public class AJAXResult  {    private AJAXResult()    {    }    private bool iserror = false;    /// <summary>    /// 是否产生错误    /// </summary>    public bool IsError { get { return iserror; } }    /// <summary>    /// 错误信息,或者成功信息    /// </summary>    public string Message { get; set; }    /// <summary>    /// 成功可能时返回的数据    /// </summary>    public object Data { get; set; }    #region Error    public static AJAXResult Error()    {      return new AJAXResult()      {        iserror = true      };    }    public static AJAXResult Error(string message)    {      return new AJAXResult()      {        iserror = true,Message = message      };    }    #endregion    #region Success    public static AJAXResult Success()    {      return new AJAXResult()      {        iserror = false      };    }    public static AJAXResult Success(string message)    {      return new AJAXResult()      {        iserror = false,Message = message      };    }    public static AJAXResult Success(object data)    {      return new AJAXResult()      {        iserror = false,Data = data      };    }    public static AJAXResult Success(object data,string message)    {      return new AJAXResult()      {        iserror = false,Data = data,Message = message      };    }    #endregion    /// <summary>    /// 序列化    /// </summary>    /// <returns></returns>    public overrIDe string ToString()    {      return new JavaScriptSerializer().Serialize(this);    }  }}
': case '\t': break; default: //值开头。。 isError = (!JsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);// break; } //if (isError) //{ //} } } /// <summary> /// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理) /// </summary> private static bool SetCharState(char c,ref CharState cs) { cs.CheckIsError(c); switch (c) { case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] #region 大括号 if (cs.keyStart <= 0 && cs.valueStart <= 0) { cs.keyStart = 0; cs.valueStart = 0; if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; } else { cs.state = 0; } cs.JsonStart = true;//开始。 return true; } #endregion break; case '}': #region 大括号结束 if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.JsonStart) { cs.JsonStart = false;//正常结束。 cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; cs.setDicValue = true; return true; } // cs.isError = !cs.JsonStart && cs.state == 0; #endregion break; case '[': #region 中括号开始 if (!cs.JsonStart) { cs.arrayStart = true; return true; } else if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; return true; } #endregion break; case ']': #region 中括号结束 if (cs.arrayStart && !cs.JsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。 { cs.keyStart = 0; cs.valueStart = 0; cs.arrayStart = false; return true; } #endregion break; case '"': case '\'': #region 引号 if (cs.JsonStart || cs.arrayStart) { if (cs.state == 0)//key阶段,有可能是数组["aa",{}] { if (cs.keyStart <= 0) { cs.keyStart = (c == '"' ? 3 : 2); return true; } else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.keyStart = -1; return true; } else { cs.escapeChar = false; } } } else if (cs.state == 1 && cs.JsonStart)//值阶段必须是Json开始了。 { if (cs.valueStart <= 0) { cs.valueStart = (c == '"' ? 3 : 2); return true; } else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.valueStart = -1; return true; } else { cs.escapeChar = false; } } } } #endregion break; case ':': #region 冒号 if (cs.JsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0) { if (cs.keyStart == 1) { cs.keyStart = -1; } cs.state = 1; return true; } // cs.isError = !cs.JsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1); #endregion break; case ',': #region 逗号 //["aa",{aa:12,}] if (cs.JsonStart) { if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1) { cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; //if (cs.valueStart == 1) //{ // cs.valueStart = 0; //} cs.setDicValue = true; return true; } } else if (cs.arrayStart && cs.keyStart <= 2) { cs.keyStart = 0; //if (cs.keyStart == 1) //{ // cs.keyStart = -1; //} return true; } #endregion break; case ' ': case '\r': case '\n'://[ "a",\r\n{} ] case '': case '\t': if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.JsonStart && { return true;//跳过空格。 } break; default: //值开头。。 if (c == '\') //转义符号 { if (cs.escapeChar) { cs.escapeChar = false; } else { cs.escapeChar = true; return true; } } else { cs.escapeChar = false; } if (cs.JsonStart || cs.arrayStart) // Json 或数组开始了。 { if (cs.keyStart <= 0 && cs.state == 0) { cs.keyStart = 1;//无引号的 } else if (cs.valueStart <= 0 && cs.state == 1 && cs.JsonStart)//只有Json开始才有值。 { cs.valueStart = 1;//无引号的 } } break; } return false; } }}

三、JsonSplit:判断字符串是否为Json

四、AJAXResult:前台AJAX请求的统一返回结果类

[+++]

常用的一些Json *** 作类,留着备用,需要的朋友的直接拿去用吧。

总结

以上是内存溢出为你收集整理的C# JsonHelper *** 作辅助类,拿来直接用全部内容,希望文章能够帮你解决C# JsonHelper *** 作辅助类,拿来直接用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 165, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
C# JsonHelper *** 作辅助类,拿来直接用_C_内存溢出

C# JsonHelper *** 作辅助类,拿来直接用

C# JsonHelper  *** 作辅助类,拿来直接用,第1张

概述四个主要 *** 作类:JsonConverter、JsonHelper、JsonSplit、AjaxResult一、JsonConverter:自定义查询对象转换动态类、object动态类转换json包、json转换object动态类、DataReader转换为Json、DataSet转换为Json、Da

四个主要 *** 作类:JsonConverter 、JsonHelper 、JsonSplit 、AJAXResult

一、JsonConverter:

自定义查询对象转换动态类、object动态类转换Json包、Json转换object动态类、DataReader转换为Json、DataSet转换为Json、Datatable转成Json、Datatable转换为Json 、格式化字符型日期型布尔型、过滤特殊字符等

using System;using System.Collections.Generic;using System.Text;using System.Data;using System.linq;using System.Web.Script.Serialization;using System.Collections;namespace Common{  public class JsonConverter  {        /// <summary>    /// 自定义查询对象转换动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj"></param>    /// <returns></returns>    public static dynamic JsonClass(object obj)     {      return ConvertJson(Serialize(obj,true));    }    /// <summary>    /// object动态类转换Json包    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="obj">对象</param>    /// <param name="DateConvert">时间戳是否转换成日期类型</param>    /// <returns></returns>    public static string Serialize(object obj,bool DateConvert = false)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      var str = Jss.Serialize(obj);      if (DateConvert)      {        str = System.Text.RegularExpressions.Regex.Replace(str,@"\/Date\((\d+)\)\/",match =>        {          DateTime dt = new DateTime(1970,1,1);          dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));          dt = dt.TolocalTime();          return dt.ToString("yyyy-MM-dd HH:mm:ss");        });      }      return str;    }    /// <summary>    /// Json转换object动态类    /// add yuangang by 2015-05-19    /// </summary>    /// <param name="Json"></param>    /// <returns></returns>    public static dynamic ConvertJson(string Json)    {      JavaScriptSerializer Jss = new JavaScriptSerializer();      Jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });      dynamic dy = Jss.Deserialize(Json,typeof(object)) as dynamic;      return dy;    }    /// <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      /// add yuangang by 2015-05-19    /// </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>     /// Datatable转成Json      /// add yuangang by 2015-05-19    /// </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>      /// Datatable转换为Json      /// add yuangang by 2015-05-19    /// </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>     /// 格式化字符型、日期型、布尔型     /// add yuangang by 2015-05-19    /// </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>     /// 过滤特殊字符     /// add yuangang by 2015-05-19    /// </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 '
using System.Collections.Generic;using System.Text;using Newtonsoft.Json;using System.Runtime.Serialization.Json;using System.IO;namespace Common{  /// <summary>  /// 提供了一个关于Json的辅助类  /// </summary>  public class JsonHelper  {    #region Method    /// <summary>    /// 类对像转换成Json格式    /// </summary>     /// <returns></returns>    public static string ToJson(object t)    {     return JsonConvert.SerializeObject(t,Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include });    }    /// <summary>    /// 类对像转换成Json格式    /// </summary>    /// <param name="t"></param>    /// <param name="HasNullignore">是否忽略NulL值</param>    /// <returns></returns>    public static string ToJson(object t,bool HasNullignore)    {      if (HasNullignore)        return JsonConvert.SerializeObject(t,new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });      else        return ToJson(t);    }    /// <summary>    /// Json格式转换    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strjson"></param>    /// <returns></returns>    public static T FromJson<T>(string strjson) where T : class    {      if (!strjson.IsNullOrEmpty())        return JsonConvert.DeserializeObject<T>(strjson);      return null;    }    /// <summary>    /// 功能描述:将List转换为Json    /// </summary>    /// <param name="a"></param>    /// <returns></returns>    public static string ListToJson(IList<object> a)    {      DataContractJsonSerializer Json = new DataContractJsonSerializer(a.GetType());      string szJson = "";      //序列化      using (MemoryStream stream = new MemoryStream())      {        Json.WriteObject(stream,a);        szJson = EnCoding.UTF8.GetString(stream.ToArray());      }      return szJson;    }    #endregion    #region Property    /// <summary>    /// 数据状态    /// </summary>    public string Status { get; set; }    /// <summary>    /// 提示信息    /// </summary>    public string Msg { get; set; }    /// <summary>    /// 回传URL    /// </summary>    public string ReUrl { get; set; }    /// <summary>    /// 数据包    /// </summary>    public object Data { get; set; }    #endregion  }}
': sb.Append("\0"); break; default: sb.Append(c); break; } } return sb.ToString(); } public static string GetDataGrIDJsonByDataSet(DataSet ds,string totalProperty,string root) { return GetDataGrIDJsonByDatatable(ds.tables[0],totalProperty,root); } public static string GetDataGrIDJsonByDatatable(Datatable dt,string root) { StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("({\"" + totalProperty + "\":\"" + dt.Rows.Count + "\","); JsonBuilder.Append("\""); JsonBuilder.Append(root); JsonBuilder.Append("\":["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\""); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\":\""); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\","); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("},"); } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); JsonBuilder.Append("})"); return JsonBuilder.ToString(); } public static string GetTreeJsonByDataSet(DataSet ds) { return GetTreeJsonByDatatable(ds.tables[0]); } public static string GetTreeJsonByDatatable(Datatable datatable) { Datatable dt = FormatDatatableForTree(datatable); StringBuilder JsonBuilder = new StringBuilder(); JsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { JsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { JsonBuilder.Append("\'"); if (dt.Columns[j].Columnname == "leaf") { string leafValue = dt.Rows[i][j].ToString(); if (!string.IsNullOrEmpty(leafValue)) { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Remove(JsonBuilder.Length - 1,1); } } else if (dt.Columns[j].Columnname == "customUrl") { JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append(":\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } else { JsonBuilder.Append(dt.Columns[j].Columnname); JsonBuilder.Append("\':\'"); JsonBuilder.Append(dt.Rows[i][j].ToString()); JsonBuilder.Append("\',"); } } JsonBuilder.Remove(JsonBuilder.Length - 1,1); JsonBuilder.Append("]"); return JsonBuilder.ToString(); } private static Datatable FormatDatatableForTree(Datatable dt) { Datatable dtTree = new Datatable(); dtTree.Columns.Add("ID",typeof(string)); dtTree.Columns.Add("text",typeof(string)); dtTree.Columns.Add("leaf",typeof(string)); dtTree.Columns.Add("cls",typeof(string)); dtTree.Columns.Add("customUrl",typeof(string)); dtTree.AcceptChanges(); for (int i = 0; i < dt.Rows.Count; i++) { DaTarow drTree = dtTree.NewRow(); drTree["ID"] = dt.Rows[i]["ID"].ToString(); drTree["text"] = dt.Rows[i]["text"].ToString(); if (dt.Rows[i]["leaf"].ToString() == "Y") { drTree["leaf"] = "true"; drTree["cls"] = "file"; } else { drTree["cls"] = "folder"; } drTree["customUrl"] = dt.Rows[i]["customUrl"].ToString(); dtTree.Rows.Add(drTree); } return dtTree; } } /// <summary> /// 动态JsON解析 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonObject : System.Dynamic.DynamicObject { private IDictionary<string,object> Dictionary { get; set; } public DynamicJsonObject(IDictionary<string,object> dictionary) { this.Dictionary = dictionary; } public overrIDe bool TryGetMember(System.Dynamic.GetMemberBinder binder,out object result) { result = this.Dictionary[binder.name]; if (result is IDictionary<string,object>) { result = new DynamicJsonObject(result as IDictionary<string,object>); } else if (result is ArrayList && (result as ArrayList) is IDictionary<string,object>) { result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string,object>))); } else if (result is ArrayList) { result = new List<object>((result as ArrayList).ToArray()); } return this.Dictionary.ContainsKey(binder.name); } } /// <summary> /// 动态JsON转换 /// add yuangang by 2015-05-19 /// </summary> public class DynamicJsonConverter : JavaScriptConverter { public overrIDe object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (type == typeof(object)) { return new DynamicJsonObject(dictionary); } return null; } public overrIDe IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer) { throw new NotImplementedException(); } public overrIDe IEnumerable<Type> SupportedTypes { get { return new System.Collections.ObjectModel.ReadonlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); } } }}

二、JsonHelper:Json的辅助

using System;using System.Collections.Generic;using System.linq;using System.Web;namespace Common{  /// <summary>  /// 判断字符串是否为JsON  /// </summary>  public class JsonSplit  {    private static bool IsJsonStart(ref string Json)    {      if (!string.IsNullOrEmpty(Json))      {        Json = Json.Trim('\r','\n',' ');        if (Json.Length > 1)        {          char s = Json[0];          char e = Json[Json.Length - 1];          return (s == '{' && e == '}') || (s == '[' && e == ']');        }      }      return false;    }    public static bool IsJson(string Json)    {      int errIndex;      return IsJson(Json,out errIndex);    }    public static bool IsJson(string Json,out int errIndex)    {      errIndex = 0;      if (IsJsonStart(ref Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (SetCharState(c,ref cs) && cs.childrenStart)//设置关键符号状态。          {            string item = Json.Substring(i);            int err;            int length = GetValueLength(item,true,out err);            cs.childrenStart = false;            if (err > 0)            {              errIndex = i + err;              return false;            }            i = i + length - 1;          }          if (cs.isError)          {            errIndex = i;            return false;          }        }        return !cs.arrayStart && !cs.JsonStart;      }      return false;    }    /// <summary>    /// 获取值的长度(当Json值嵌套以"{"或"["开头时)    /// </summary>    private static int GetValueLength(string Json,bool breakOnErr,out int errIndex)    {      errIndex = 0;      int len = 0;      if (!string.IsNullOrEmpty(Json))      {        CharState cs = new CharState();        char c;        for (int i = 0; i < Json.Length; i++)        {          c = Json[i];          if (!SetCharState(c,ref cs))//设置关键符号状态。          {            if (!cs.JsonStart && !cs.arrayStart)//Json结束,又不是数组,则退出。            {              break;            }          }          else if (cs.childrenStart)//正常字符,值状态下。          {            int length = GetValueLength(Json.Substring(i),breakOnErr,out errIndex);//递归子值,返回一个长度。。。            cs.childrenStart = false;            cs.valueStart = 0;            //cs.state = 0;            i = i + length - 1;          }          if (breakOnErr && cs.isError)          {            errIndex = i;            return i;          }          if (!cs.JsonStart && !cs.arrayStart)//记录当前结束位置。          {            len = i + 1;//长度比索引+1            break;          }        }      }      return len;    }    /// <summary>    /// 字符状态    /// </summary>    private class CharState    {      internal bool JsonStart = false;//以 "{"开始了...      internal bool setDicValue = false;// 可以设置字典值了。      internal bool escapeChar = false;//以"\"转义符号开始了      /// <summary>      /// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。      /// </summary>      internal bool arrayStart = false;//以"[" 符号开始了      internal bool childrenStart = false;//子级嵌套开始了。      /// <summary>      /// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】      /// </summary>      internal int state = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int keyStart = 0;      /// <summary>      /// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】      /// </summary>      internal int valueStart = 0;      internal bool isError = false;//是否语法错误。      internal voID CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)      {        if (keyStart > 1 || valueStart > 1)        {          return;        }        //示例 ["aa",{"bbbb":123,"fff","ddd"}]         switch (c)        {          case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]            isError = JsonStart && state == 0;//重复开始错误 同时不是值处理。            break;          case '}':            isError = !JsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}            break;          case '[':            isError = arrayStart && state == 0;//重复开始错误            break;          case ']':            isError = !arrayStart || JsonStart;//重复开始错误 或者 Json 未结束            break;          case '"':          case '\'':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              //重复开始 [""",{"" "}]              isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);            }            if (!isError && arrayStart && !JsonStart && c == '\'')//['aa',{}]            {              isError = true;            }            break;          case ':':            isError = !JsonStart || state == 1;//重复出现。            break;          case ',':            isError = !(JsonStart || arrayStart); //Json 或数组开始。            if (!isError)            {              if (JsonStart)              {                isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。              }              else if (arrayStart)//["aa,] [,] [{},{}]              {                isError = keyStart == 0 && !setDicValue;              }            }            break;          case ' ':          case '\r':          case '\n'://[ "a",\r\n{} ]          case '
using System.Web.Script.Serialization;namespace Common{  /// <summary>  /// 前台AJAX请求的统一返回结果类  /// </summary>  public class AJAXResult  {    private AJAXResult()    {    }    private bool iserror = false;    /// <summary>    /// 是否产生错误    /// </summary>    public bool IsError { get { return iserror; } }    /// <summary>    /// 错误信息,或者成功信息    /// </summary>    public string Message { get; set; }    /// <summary>    /// 成功可能时返回的数据    /// </summary>    public object Data { get; set; }    #region Error    public static AJAXResult Error()    {      return new AJAXResult()      {        iserror = true      };    }    public static AJAXResult Error(string message)    {      return new AJAXResult()      {        iserror = true,Message = message      };    }    #endregion    #region Success    public static AJAXResult Success()    {      return new AJAXResult()      {        iserror = false      };    }    public static AJAXResult Success(string message)    {      return new AJAXResult()      {        iserror = false,Message = message      };    }    public static AJAXResult Success(object data)    {      return new AJAXResult()      {        iserror = false,Data = data      };    }    public static AJAXResult Success(object data,string message)    {      return new AJAXResult()      {        iserror = false,Data = data,Message = message      };    }    #endregion    /// <summary>    /// 序列化    /// </summary>    /// <returns></returns>    public overrIDe string ToString()    {      return new JavaScriptSerializer().Serialize(this);    }  }}
': case '\t': break; default: //值开头。。 isError = (!JsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);// break; } //if (isError) //{ //} } } /// <summary> /// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理) /// </summary> private static bool SetCharState(char c,ref CharState cs) { cs.CheckIsError(c); switch (c) { case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}] #region 大括号 if (cs.keyStart <= 0 && cs.valueStart <= 0) { cs.keyStart = 0; cs.valueStart = 0; if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; } else { cs.state = 0; } cs.JsonStart = true;//开始。 return true; } #endregion break; case '}': #region 大括号结束 if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.JsonStart) { cs.JsonStart = false;//正常结束。 cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; cs.setDicValue = true; return true; } // cs.isError = !cs.JsonStart && cs.state == 0; #endregion break; case '[': #region 中括号开始 if (!cs.JsonStart) { cs.arrayStart = true; return true; } else if (cs.JsonStart && cs.state == 1) { cs.childrenStart = true; return true; } #endregion break; case ']': #region 中括号结束 if (cs.arrayStart && !cs.JsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。 { cs.keyStart = 0; cs.valueStart = 0; cs.arrayStart = false; return true; } #endregion break; case '"': case '\'': #region 引号 if (cs.JsonStart || cs.arrayStart) { if (cs.state == 0)//key阶段,有可能是数组["aa",{}] { if (cs.keyStart <= 0) { cs.keyStart = (c == '"' ? 3 : 2); return true; } else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.keyStart = -1; return true; } else { cs.escapeChar = false; } } } else if (cs.state == 1 && cs.JsonStart)//值阶段必须是Json开始了。 { if (cs.valueStart <= 0) { cs.valueStart = (c == '"' ? 3 : 2); return true; } else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"')) { if (!cs.escapeChar) { cs.valueStart = -1; return true; } else { cs.escapeChar = false; } } } } #endregion break; case ':': #region 冒号 if (cs.JsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0) { if (cs.keyStart == 1) { cs.keyStart = -1; } cs.state = 1; return true; } // cs.isError = !cs.JsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1); #endregion break; case ',': #region 逗号 //["aa",{aa:12,}] if (cs.JsonStart) { if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1) { cs.state = 0; cs.keyStart = 0; cs.valueStart = 0; //if (cs.valueStart == 1) //{ // cs.valueStart = 0; //} cs.setDicValue = true; return true; } } else if (cs.arrayStart && cs.keyStart <= 2) { cs.keyStart = 0; //if (cs.keyStart == 1) //{ // cs.keyStart = -1; //} return true; } #endregion break; case ' ': case '\r': case '\n'://[ "a",\r\n{} ] case '': case '\t': if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.JsonStart && { return true;//跳过空格。 } break; default: //值开头。。 if (c == '\') //转义符号 { if (cs.escapeChar) { cs.escapeChar = false; } else { cs.escapeChar = true; return true; } } else { cs.escapeChar = false; } if (cs.JsonStart || cs.arrayStart) // Json 或数组开始了。 { if (cs.keyStart <= 0 && cs.state == 0) { cs.keyStart = 1;//无引号的 } else if (cs.valueStart <= 0 && cs.state == 1 && cs.JsonStart)//只有Json开始才有值。 { cs.valueStart = 1;//无引号的 } } break; } return false; } }}

三、JsonSplit:判断字符串是否为Json

四、AJAXResult:前台AJAX请求的统一返回结果类

常用的一些Json *** 作类,留着备用,需要的朋友的直接拿去用吧。

总结

以上是内存溢出为你收集整理的C# JsonHelper *** 作辅助类,拿来直接用全部内容,希望文章能够帮你解决C# JsonHelper *** 作辅助类,拿来直接用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1259250.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存