欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# JSON格式化转换辅助类 ConvertJson

程序员文章站 2023-10-31 16:30:40
可能我们用惯了 newtonsoft.json.dll 等第三方的类库来实现序列化等类似的操作,但是有时只是简单的用一下,感觉没必要那么费事,所谓杀鸡焉用牛刀,自制个小刀即...

可能我们用惯了 newtonsoft.json.dll 等第三方的类库来实现序列化等类似的操作,但是有时只是简单的用一下,感觉没必要那么费事,所谓杀鸡焉用牛刀,自制个小刀即可。

代码分享给大家,如下:

using system;
using system.collections.generic;
using system.text;
using system.data;
using system.reflection;
using system.collections;
using system.data.common;
 
public class convertjson
{
  #region 私有方法
  /// <summary>
  /// 过滤特殊字符
  /// </summary>
  private 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;
        default:
          sb.append(c); break;
      }
    }
    return sb.tostring();
  }
 
  /// <summary>
  /// 格式化字符型、日期型、布尔型
  /// </summary>
  private static string stringformat(string str, type type)
  {
    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(string) && string.isnullorempty(str))
    {
      str = "\"" + str + "\"";
    }
    return str;
  }
  #endregion
 
  #region list转换成json
  /// <summary>
  /// list转换成json
  /// </summary>
  public static string listtojson<t>(ilist<t> list)
  {
    object obj = list[0];
    return listtojson<t>(list, obj.gettype().name);
  }
 
  /// <summary>
  /// list转换成json
  /// </summary>
  public static string listtojson<t>(ilist<t> list, string jsonname)
  {
    stringbuilder json = new stringbuilder();
    if (string.isnullorempty(jsonname)) jsonname = list[0].gettype().name;
    json.append("{\"" + jsonname + "\":[");
    if (list.count > 0)
    {
      for (int i = 0; i < list.count; i++)
      {
        t obj = activator.createinstance<t>();
        propertyinfo[] pi = obj.gettype().getproperties();
        json.append("{");
        for (int j = 0; j < pi.length; j++)
        {
          type type = pi[j].getvalue(list[i], null).gettype();
          json.append("\"" + pi[j].name.tostring() + "\":" + stringformat(pi[j].getvalue(list[i], null).tostring(), type));
 
          if (j < pi.length - 1)
          {
            json.append(",");
          }
        }
        json.append("}");
        if (i < list.count - 1)
        {
          json.append(",");
        }
      }
    }
    json.append("]}");
    return json.tostring();
  }
  #endregion
 
  #region 对象转换为json
  /// <summary>
  /// 对象转换为json
  /// </summary>
  /// <param name="jsonobject">对象</param>
  /// <returns>json字符串</returns>
  public static string tojson(object jsonobject)
  {
    string jsonstring = "{";
    propertyinfo[] propertyinfo = jsonobject.gettype().getproperties();
    for (int i = 0; i < propertyinfo.length; i++)
    {
      object objectvalue = propertyinfo[i].getgetmethod().invoke(jsonobject, null);
      string value = string.empty;
      if (objectvalue is datetime || objectvalue is guid || objectvalue is timespan)
      {
        value = "'" + objectvalue.tostring() + "'";
      }
      else if (objectvalue is string)
      {
        value = "'" + tojson(objectvalue.tostring()) + "'";
      }
      else if (objectvalue is ienumerable)
      {
        value = tojson((ienumerable)objectvalue);
      }
      else
      {
        value = tojson(objectvalue.tostring());
      }
      jsonstring += "\"" + tojson(propertyinfo[i].name) + "\":" + value + ",";
    }
    jsonstring.remove(jsonstring.length - 1, jsonstring.length);
    return jsonstring + "}";
  }
  #endregion
 
  #region 对象集合转换json
  /// <summary>
  /// 对象集合转换json
  /// </summary>
  /// <param name="array">集合对象</param>
  /// <returns>json字符串</returns>
  public static string tojson(ienumerable array)
  {
    string jsonstring = "[";
    foreach (object item in array)
    {
      jsonstring += tojson(item) + ",";
    }
    jsonstring.remove(jsonstring.length - 1, jsonstring.length);
    return jsonstring + "]";
  }
  #endregion
 
  #region 普通集合转换json
  /// <summary>
  /// 普通集合转换json
  /// </summary>
  /// <param name="array">集合对象</param>
  /// <returns>json字符串</returns>
  public static string toarraystring(ienumerable array)
  {
    string jsonstring = "[";
    foreach (object item in array)
    {
      jsonstring = tojson(item.tostring()) + ",";
    }
    jsonstring.remove(jsonstring.length - 1, jsonstring.length);
    return jsonstring + "]";
  }
  #endregion
 
  #region dataset转换为json
  /// <summary>
  /// dataset转换为json
  /// </summary>
  /// <param name="dataset">dataset对象</param>
  /// <returns>json字符串</returns>
  public static string tojson(dataset dataset)
  {
    string jsonstring = "{";
    foreach (datatable table in dataset.tables)
    {
      jsonstring += "\"" + table.tablename + "\":" + tojson(table) + ",";
    }
    jsonstring = jsonstring.trimend(',');
    return jsonstring + "}";
  }
  #endregion
 
  #region datatable转换为json
  /// <summary>
  /// datatable转换为json
  /// </summary>
  /// <param name="table">datatable对象</param>
  /// <returns>json字符串</returns>
  public static string tojson(datatable dt)
  {
    stringbuilder jsonstring = new stringbuilder();
    jsonstring.append("[");
    datarowcollection drc = dt.rows;
    for (int i = 0; i < drc.count; i++)
    {
      jsonstring.append("{");
      for (int j = 0; j < dt.columns.count; j++)
      {
        string strkey = dt.columns[j].columnname;
        string strvalue = drc[i][j].tostring();
        type type = dt.columns[j].datatype;
        jsonstring.append("\"" + strkey + "\":");
        strvalue = stringformat(strvalue, type);
        if (j < dt.columns.count - 1)
        {
          jsonstring.append(strvalue + ",");
        }
        else
        {
          jsonstring.append(strvalue);
        }
      }
      jsonstring.append("},");
    }
    jsonstring.remove(jsonstring.length - 1, 1);
    jsonstring.append("]");
    return jsonstring.tostring();
  }
 
  /// <summary>
  /// datatable转换为json
  /// </summary>
  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].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();
  }
  #endregion
 
  #region datareader转换为json
  /// <summary>
  /// datareader转换为json
  /// </summary>
  /// <param name="datareader">datareader对象</param>
  /// <returns>json字符串</returns>
  public static string tojson(dbdatareader datareader)
  {
    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("},");
    }
    datareader.close();
    jsonstring.remove(jsonstring.length - 1, 1);
    jsonstring.append("]");
    return jsonstring.tostring();
  }
  #endregion
}