Generic Class to get JSON from DataSet: C#, JSON


Introduction:

We have a requirement for our REST API to send and accept the data as JSON object. So I have created a generic class that can convert DataSet or DataTable into JSON Objects. You can also define the Relationship between the dataTables So that you can get hierarchical JSON object from the class methods.

Methods in Class:
**
**1) public System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, object>> ConvertDataSettoList(System.Data.DataSet DS)
2) public string ConvertDataSettoString(System.Data.DataSet DS)
3) public System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, object>> ConvertDataTabletoList(System.Data.DataTable dt)
4) public string ds2json(System.Data.DataSet ds)
5) public string dt2Json(System.Data.DataTable dt)
6) public System.Data.DataTable generateHeaderDT(string status, string messageTitle, string messageDescription)
7) public string generateReturnJSON(System.Data.DataTable ResponseDT, System.Data.DataTable dtheader, string strResponseNode)

Sample Code to use these Methods:

01.DataTable DTTracks = AppDB.getPlanTracks();
02.        DataTable DTPlan = AppDB.getDayPlan();
03.        DataSet DSTrackPlan = new  DataSet();
04.

05.        DataTable dtHS = DTTracks.Copy();
06.        dtHS.TableName = "Track";
07.        DSTrackPlan.Tables.Add(dtHS);
08. 
09.        DataTable DTStudent = DTPlan.Copy();
10.        DTStudent.TableName = "Plan";
11.        /// //////////////////////////////////////// END //////////////////////////////////////// 
12.        DSTrackPlan.Tables.Add(DTStudent);
13. 
14.        DataRelation objRelation = new  DataRelation("processData",
15.            new DataColumn[] { DSTrackPlan.Tables["Track"].Columns["S_P_ID"] },
16.            new DataColumn[] { DSTrackPlan.Tables["Plan"].Columns["S_P_ID"] }
17.            );
18. 
19.        DSTrackPlan.Relations.Add(objRelation);
20. 
21.        if (DSTrackPlan.Tables[0].Rows.Count > 0)
22.        {
23.            DataTable dtheader = objJSHelper.generateHeaderDT("00", "", "");
24.            DataSet DS = new  DataSet();
25. 
26.            dtheader.TableName = "Header";
27.            DS.Tables.Add(dtheader);
28.            resultSet = "[{\"Header\": "  + objJSHelper.dt2Json(dtheader) + ",";
29.            resultSet += "\"Body\": {\"ServerDate\": [{\"serverDateTime\": \"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "\"}],\"Track_Plan\":"  + objJSHelper.ConvertDataSettoString(DSTrackPlan) + "}}]";
30.        }
31.        else
32.        {
33.            resultSet = objJSHelper.dt2Json(objJSHelper.generateHeaderDT("01", "no data found", ""));
34.        }

DLL FIle Link:
**JSONCustomHelper
**