C#实现集合转换成json格式数据

本文实例讲述了C#实现集合转换成json格式数据的方法。分享给大家供大家参考,具体如下:

/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt)
{
  if (dt != null && dt.Rows.Count > 0)
  {
    StringBuilder jsonBuilder = new StringBuilder();
    jsonBuilder.Append("{\"");
    jsonBuilder.Append("data");
    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(jsonStringFromat(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();
  }
  else
  {
    return "";
  }
}
/// <summary>
/// Enumerable转成JSON
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static string EnumerableToJson(IEnumerable list)
{
  StringBuilder json = new StringBuilder();
  int i = 0;
  if (list != null)
  {
    json.Append("{\"data\":[");
    foreach (var item in list)
    {
      json.Append("{");
      PropertyInfo[] pi = item.GetType().GetProperties();
      int j = 0;
      foreach (var p in pi)
      {
        if (j < pi.Length - 1)
        {
          json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\",");
        }
        else
        {
          json.Append("\"" + p.Name.ToString() + "\":\"" + jsonStringFromat(p.GetValue(item, null).ToString()) + "\"");
        }
        j++;
      }
      i++;
      json.Append("},");
    }
    json.Remove(json.Length - 1, 1);
    json.Append("]}");
  }
  if (i != 0)
    return json.ToString();
  else
    return "";
}

 

posted @ 2018-05-09 10:51  莫小麦  阅读(5475)  评论(0编辑  收藏  举报