DataTable转Json方法

public static string CreateJsonParameters(DataTable dt)
 {
        StringBuilder JsonString = new StringBuilder();
        //Exception Handling       
        if (dt != null && dt.Rows.Count > 0)
        {
            JsonString.Append("{ ");
            JsonString.Append("\"" + dt.TableName + "\":[ ");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0)
                {
                    JsonString.Append(",");
                }
                JsonString.Append("{ ");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j > 0)
                    {
                        JsonString.Append(",");
                    }
                    JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
 
                }
                JsonString.Append("} ");
            }
            JsonString.Append("]}");
            return JsonString.ToString();
        }
        else
        {
            return null;
        }
 }

你可能感兴趣的:(DataTable转Json方法)