程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# JsonHelper 操作幫助類,拿來直接用

C# JsonHelper 操作幫助類,拿來直接用

編輯:C#入門知識

C# JsonHelper 操作幫助類,拿來直接用。本站提示廣大學習愛好者:(C# JsonHelper 操作幫助類,拿來直接用)文章只能為提供參考,不一定能成為您想要的結果。以下是C# JsonHelper 操作幫助類,拿來直接用正文


四個重要操作類:JsonConverter 、JsonHelper 、JsonSplit 、AjaxResult

1、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.WordStr(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 '\0':
            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 totalProperty, 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("},");
      }
      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) })); }
    }
  }
}

2、JsonHelper:json的幫助類

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, Newtonsoft.Json.Formatting.Indented, 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

  }
}

3、JsonSplit:斷定字符串能否為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 '\0':
          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 '\0':
        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;
    }
  }
}

4、AjaxResult:前台Ajax要求的同一前往成果類

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);
    }
  }
}

經常使用的一些Json操作類,留著備用,須要的同伙的直接拿去用吧。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved