0

is it possible to load data in two connected tables in SQL Server database and convert it in json format? its like you have Data (in table1) and the sub arrays of that data is on the table2.

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

I just want to create a flexible menu control that its data loaded from the Database.

Please help me...

np_6
  • 514
  • 1
  • 6
  • 19
user3274033
  • 29
  • 2
  • 11

2 Answers2

0

First you need get a data from Table Twice . Like my Example

i'm use struct do a json object base And use two SqlDataSource get a Table1 & Table2 Data

Table2 Data will filter by Table1 .

Last , I save Table2 Data in my struct List & Ditionary

you can refer 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);
}
Community
  • 1
  • 1
King Jk
  • 1,069
  • 14
  • 22
0

If you use SQL Server 2016 or Azure SQL Database then you can use FOR JSON AUTO:

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

In older version you need to do it in app layer. Maybe you can use FOR XML AUTO that exists since forever and then transform XML to JSON using some XSLT in app code?

Jovan MSFT
  • 13,232
  • 4
  • 40
  • 55