DataTable转JSON

//DataTable转成Json
                str_Json = DataTableToJson(dt, "ID,Name,Sex"); 调用

 ///<summary>
    ///
    /// </summary>
    ///<param name="dt">DataTable数据</param>
    ///<param name="fields">字段,可选.格式为 "ID,Name,Sex"</param>
    ///<returns></returns>
    public static string DataTableToJson(DataTable dt, string fields)
    {
        if (fields == "")
        {
            foreach (DataColumn dc in dt.Columns)
            {
                if (fields != "") fields += ",";
                fields += dc.ColumnName;
            }
        }

        string[] fieldsArr = fields.Split(",".ToCharArray());
        StringBuilder Json = new StringBuilder();
        Json.Append("[");
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Json.Append("{");
                for (int j = 0; j < fieldsArr.Length; j++)
                {
                    Json.Append("\"" + fieldsArr[j] + "\":\"" + dt.Rows[i][fieldsArr[j]].ToString() + "\"");
                    if (j < fieldsArr.Length - 1)
                        Json.Append(",");
                }
                Json.Append("}");
                if (i < dt.Rows.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]");
        return Json.ToString();
    }

posted @ 2012-02-22 16:18  殇伈de錑婲  阅读(214)  评论(0编辑  收藏  举报