csharp_ToJson的正确写法

网上搜的,但有问题,已经改好。。。现在这个是正确的

public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            //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();
                        if (type.Name.ToString() == "Int32")
                        {
                            Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + String.Format(dt.Rows[i][j].ToString(), type));
                        }
                        else
                        {
                            Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + String.Format(dt.Rows[i][j].ToString(), type));
                        }
                        if (j < dt.Columns.Count - 1)
                        {
                            if (type.Name.ToString() == "Int32")
                            {
                                Json.Append(",");
                            }
                            else
                            {
                                Json.Append("\",");
                            }
                        }
                    }
                    Json.Append("\"}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            //Json.Append("}");
            return Json.ToString();
        }
    }
}

上一篇:IIS7 WebAPI 404.0 Error


下一篇:POJ1125 Stockbroker Grapevine(spfa枚举)