递归序列化多个Datatable层次结构到JSON对象
本文关键字:JSON 对象 层次结构 Datatable 序列化 递归 | 更新日期: 2023-09-27 18:19:06
我想将多个数据表序列化为JSON,这些数据表是相互关联的,可能会有额外的表都设置在映射表中。在本例中,我有3个datatable。
- 表A作为父表
- 表B作为表A的子表
- 表C作为表B的子表
JSON输出应该是
{
"TableA": [
{
"ID": "2490",
"TYPE": "Electronic",
"TableB": [
{
"ID": "2490",
"ITEM": "XMT123",
"RECEIPT_NUM": "59",
"TableC": [
{
"ID": "2490",
"ITEM": "XMT123",
"QUANTITY": "164"
}
]
},
{
"ID": "2491",
"ITEM": "XMT234",
"RECEIPT_NUM": "12",
"TableC": [
{
"ID": "2491",
"ITEM": "XMT234",
"QUANTITY": "92"
}
]
}
]
},
{
"ID": "2491",
"TYPE": "Electronic",
"TableB": [
{
"ID": "2491",
"ITEM": "XMT456",
"RECEIPT_NUM": "83",
"TableC": [
{
"ID": "2491",
"ITEM": "XMT456",
"QUANTITY": "261"
}
]
},
{
"ID": "2492",
"ITEM": "XMT567",
"RECEIPT_NUM": "77",
"TableC": [
{
"ID": "2492",
"ITEM": "XMT567",
"QUANTITY": "70"
}
]
}
]
}
]
}
我已经尝试过这样的代码,但它似乎不起作用
static void dataToJson(string connection_string, string query, string table_name)
{
try
{
JArray jArray = new JArray();
DataTable tbl = new DataTable();
DataTable inner_tbl = new DataTable();
SqlConnection conn = new SqlConnection(connection_string);
conn.Open();
var adapter = new SqlDataAdapter(query, conn); // query to get parent
adapter.Fill(tbl);
foreach (DataRow row in tbl.Rows)
{
JObject jo = new JObject();
foreach (DataColumn col in tbl.Columns)
{
jo.Add(new JProperty(col.ColumnName.ToString(), row[col].ToString()));
}
jArray.Add(jo);
query = "i have query to get child";
dataToJson(connection_string, query, table_child);
}
}
catch (Exception e)
{
WriteLog(e.Message, GetCurrentMethod(e));
}
}
您必须在此递归方法中传递父类或返回子类。此外,如果所有表都在同一个数据库中,则不必每次都打开SqlConnection
。
下面是传递父元素的例子:
// Caller
JObject root = new JObject();
using (SqlConnection conn = new SqlConnection(connection_string))
{
conn.Open();
dataToJson(root, conn, query, "TableA");
}
Console.WriteLine(root.ToString());
static void dataToJson(JObject parent, SqlConnection conn, string query, string table_name)
{
if (string.IsNullOrEmpty(table_name)) { return; }
try
{
JArray jArray = new JArray();
DataTable tbl = new DataTable();
//DataTable inner_tbl = new DataTable();
//SqlConnection conn = new SqlConnection(connection_string);
//conn.Open();
var adapter = new SqlDataAdapter(query, conn); // query to get parent
adapter.Fill(tbl);
foreach (DataRow row in tbl.Rows)
{
JObject jo = new JObject();
foreach (DataColumn col in tbl.Columns)
{
jo.Add(new JProperty(col.ColumnName.ToString(), row[col].ToString()));
}
query = "i have query to get child";
// Set the child table name to "table_child"
dataToJson(jo, conn, query, table_child); // Pass the JObject as the parent
jArray.Add(jo);
parent.Add(new JProperty(table_name, jArray));
}
}
catch (Exception e)
{
WriteLog(e.Message, GetCurrentMethod(e));
}
}
顺便说一下,我不确定如何获得子表的名称,所以我使用以下字典进行测试。
static Dictionary<string, string> table_hierarchy = new Dictionary<string, string>();
// Initialize
table_hierarchy.Add("TableA", "TableB");
table_hierarchy.Add("TableB", "TableC");
table_hierarchy.Add("TableC", "");