将多个数据表序列化为JSON

本文关键字:JSON 序列化 数据表 | 更新日期: 2023-09-27 18:18:19

我想将两个DataTables序列化为JSON,但我不能这样做。我看了一些例子,但我解不出这个问题。请帮帮我。

My datatable:

    SqlDataAdapter adp1 = new SqlDataAdapter("select * from table1", con);
    SqlDataAdapter adp2 = new SqlDataAdapter("select * from table2", con);
    DataTable dt1 = new DataTable();
    DataTable dt2 = new DataTable();
    adp1.Fill(dt1);
    adp2.Fill(dt2);

我想得到这个结果:

var Json_Array = {
        "DataTable1":
            [
                {
                    "Id": "1",
                    "Name": "John"                       
                },
                {
                    "Id": "2",
                    "Name": "Mike"                        
                }
            ],
        "DataTable2":
            [
                {
                    "Mark": "Opel",
                    "Year": "1998"
                },
                {
                    "Mark": "Renault",
                    "Year": "2016"
                }
            ]
    };

将多个数据表序列化为JSON

只需将您的DataTables添加到匿名对象并使用Json序列化即可。净:

var data = new
{
    DataTable1 = dt1,
    DataTable2 = dt2
};
string json = JsonConvert.SerializeObject(data, Formatting.Indented);

小提琴:https://dotnetfiddle.net/ytKJnO

您需要创建以下类:

public class Test
{
   public DataTable[] DataTable1; 
   public DataTable[] DataTable2;
}

我写了DataTable[],因为在示例JSON中,DataTable1DataTable2字段上有数组

初始化:

var objToSerialize = new Test(){DataTable1=new []{dt1}, DataTable2=new []{dt2}};

然后用Newtosoft序列化为json。JSON:

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

您需要一个序列化器来从DataTable转换为JSON -一个这样的
序列化器是Newtonsoft。

using Newtonsoft.Json;
代码:

var oTable1 = JsonConvert.SerializeObject(dt1);
var oTable2 = JsonConvert.SerializeObject(dt2);
//Send back oTable1 and oTable2 to browser, choose your own way, e.g. 
//Response.Write(oTable1);
//Other way: Drag and drop two textbox(s) or two hiddenfield(s)
TextBox1.Text = oTable1;
TextBox2.Text = oTable2;

或:

HiddenField1.Value = oTable1;
HiddenField2.Value = oTable2;