我想将多个相互关联的数据表序列化为 JSON,并且可能会在映射表中设置其他表。在这种情况下,我有 3 个数据表。
- 表 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));
}
}