【问题标题】:ASP.NET + SQL SERVER + JSON = how to get data in two connected tables in SQL Server and load as JSON?ASP.NET + SQL SERVER + JSON = 如何在 SQL Server 的两个连接表中获取数据并加载为 JSON?
【发布时间】:2014-02-21 01:57:04
【问题描述】:

是否可以在 SQL Server 数据库中的两个连接表中加载数据并转换为 json 格式?就像您有数据(在表 1 中)并且该数据的子数组在表 2 上。

{
    "id": "0001",   ///*** this data is from table1
    "name": "Menu1", 
    "Submenus": [  ///*** this data is from table2
        { "id": "1001", "text": "Regular" },
        { "id": "1002", "text": "Chocolate" },
        { "id": "1003", "text": "Blueberry" },
        { "id": "1004", "text": "Devil's Food" }
    ]
}

我只想创建一个灵活的菜单控件,它的数据从数据库中加载。

请帮帮我...

【问题讨论】:

    标签: asp.net sql sql-server json


    【解决方案1】:

    首先,您需要从 Table Twice 获取数据。就像我的例子

    我正在使用 struct 做一个 json 对象库并使用两个 SqlDataSource 获取一个 Table1 和 Table2 数据

    Table2 数据将按 Table1 过滤。

    最后,我将 Table2 数据保存在我的结构列表和字典中

    您可以参考ConvertDataTabletoJsonString

        public struct PersonScore
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public  List<Dictionary<string, object>> Score { get; set; }
    
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable Table1Data = (SqlDataSource1.Select(new DataSourceSelectArguments()) as DataView).Table;
        SqlDataSource2.SelectParameters["SutdentID"].DefaultValue = Table1Data.Rows[0]["ID"].ToString();
        DataView Table2Data = SqlDataSource2.Select(new DataSourceSelectArguments()) as DataView;
        DataTable DT = Table2Data.Table;
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow DR in DT.Rows)
        {
             row = new Dictionary<string, object>();
            foreach (DataColumn Col in DT.Columns)
            {
                row.Add(Col.ColumnName, DR[Col]);
            }
            rows.Add(row);
        }
        PersonScore NewPersonScore = new PersonScore
        {
            ID = Table1Data.Rows[0]["ID"].ToString(),
            Name = Table1Data.Rows[0]["StudentName"].ToString(),
            Score=rows
        };
        string jsontxt = new JavaScriptSerializer().Serialize(NewPersonScore);
        Response.Write(jsontxt);
    }
    

    【讨论】:

      【解决方案2】:

      如果您使用 SQL Server 2016 或 Azure SQL 数据库,则可以使用 FOR JSON AUTO:

      SELECT id, name, table2.id, table2.text
      FROM table1 JOIN table2 ON table1.pk = table2.fk
      FOR JSON AUTO
      

      在旧版本中,您需要在应用层执行此操作。也许您可以使用永远存在的 FOR XML AUTO,然后在应用代码中使用 XSLT 将 XML 转换为 JSON?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多