gpt4 book ai didi

c# - 如何从以变量为键的 DataTable 制作 JSON

转载 作者:行者123 更新时间:2023-11-30 15:14:59 25 4
gpt4 key购买 nike

我有一个来自数据库的查询,其中有许多行存储在 DataTable 中。

我有 40 个 ID,但每个 ID 有 300 行。数据如下所示:

DataTable data

我想从 DataTable 将其序列化为 JSON,使用 IDF_SD 作为键。

序列化 DataTable 后,我得到如下所示的 JSON:

undesirable JSON

谁能帮我解决这个问题?我将在前端将此数据用于 js 图。我想要这样的东西:

{
"ID": {
"f_sd1": {
"value": 1.555
}
"f_sd2": {
"value": xxxx
}
}
"nextID": {
"f_sd1": {
"value": 1.555
}
"f_sd2": {
"value": xxxx
}
}
}

我现在正在这样序列化它:

using (con = new OracleConnection(constr))
{
using (cmd = new OracleCommand(query, con))
{
con.Open();

OracleDataAdapter sda = new OracleDataAdapter(cmd);
sda.Fill(dt1);
var list = JsonConvert.SerializeObject(dt1, Formatting.None, new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

return Content(list, "application/json");
}
}

最佳答案

您可以使用 Linq 方法将 DataTable 的行分组到一个匿名对象结构中,然后将其序列化:

    var obj = dt1.Rows
.Cast<DataRow>()
.GroupBy(row => (int)row["ID"])
.ToDictionary(g => g.Key,
g => g.ToDictionary(row => (int)row["F_SD"],
row => new { value = (decimal)row["VAL"] }));

string json = JsonConvert.SerializeObject(obj, Formatting.Indented);

return Content(json, "application/json");

fiddle :https://dotnetfiddle.net/zWIUZ5

关于c# - 如何从以变量为键的 DataTable 制作 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53494984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com