2014-02-21 37 views
0

是否可以在SQL Server數據庫中的兩個連接表中加載數據並將其轉換爲json格式?它就像你有數據(在表1中)並且該數據的子數組在表2上。ASP.NET + SQL SERVER + JSON =如何獲取SQL Server中兩個連接表中的數據並以JSON方式加載?

{ 
    "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" } 
        ] 
    } 

我只是想創建一個靈活的菜單控件,其數據從數據庫中加載。

請幫我...

回答

0

首先,您需要從表格兩次獲取數據。像我的例子

我是使用結構做一個JSON對象,基地和使用兩個的SqlDataSource得到表1 &表2數據

表2的數據將通過表1進行篩選。

末,我省表2的數據在我的結構列表& Ditionary

你可以參考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); 
} 
0

如果你使用SQL Server 2016或Azure的SQL數據庫,那麼你可以使用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?