【发布时间】:2019-02-11 16:30:03
【问题描述】:
我正在尝试将 DataTable 转换为 JSON 文本,但如果其中一列具有表类型的数据,我会遇到问题。
DataTable TaskDetails = new DataTable(); //subtable
TaskDetails.Columns.Add("taskId", typeof(string));
TaskDetails.Columns.Add("ticketUid", typeof(string));
TaskDetails.Rows.Add(TaskID, TicketUID);
DataTable table = new DataTable(); //main table
table.Columns.Add("operationType", typeof(string));
table.Columns.Add("comment", typeof(string));
table.Columns.Add("tasks", typeof(DataTable));
table.Rows.Add(OperationType,Comment,TaskDetails); //TaskDetails table is added on the main table.
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
string response = serializer.Serialize(rows); //I'm getting an error here
错误:System.InvalidOperationException 在序列化“System.Reflection.RuntimeModule”类型的对象时检测到循环引用
我希望有 Json 格式的字符串输出。
【问题讨论】:
-
您为什么要为此使用 DataTable?为什么不直接创建一些表示信息的类,然后序列化这些类?
-
你能举个例子吗?我有点不知道该怎么做。
-
你迷失了哪一部分?你知道怎么上课吗?如何为类添加属性?如何为这些属性赋值?如何将给定的类序列化为 JSON?