I Need some help in generating JSON Files from a database table. Below is my sample json generated through tsql code (using SQL Server 2017)
{ "TBLEMPLOYEES":[
{
"ID":1,
"NAME":"SURESH",
"SALARY":1000,
"ADDRESS":{
"EMP_ADDRESS":"101 A ADDRESS1",
"OTHERS":{
"EMP_PHONE":"987-654-4567",
"EMP_CITY":"CITY1"
}
}
},
{
"ID":2,
"NAME":"RAMESH",
"SALARY":2000,
"ADDRESS":{
"EMP_ADDRESS":"125 A ADDRESS2",
"OTHERS":{
"EMP_PHONE":"588-654-4567",
"EMP_CITY":"CITY2"
}
}
}
] }
Below is the TSQL code that i'm using to generate the JSON output in SSMS
SELECT ID AS "ID", EMP_NAME AS "NAME", EMP_SALARY AS "SALARY",EMP_ADDRESS AS "ADDRESS.EMP_ADDRESS", EMP_PHONE AS "ADDRESS.OTHERS.EMP_PHONE", EMP_CITY AS "ADDRESS.OTHERS.EMP_CITY" FROM TBLEMPLOYEES FOR JSON path, root('TBLEMPLOYEES')
Now issue is when I try to use the same query from winform application using C#.net im not getting the correct Json File format. Its having no data in it.
Here is the code that i'm using
var queryWithForJson = "SELECT ID AS \"ID\", EMP_NAME AS \"NAME\", EMP_SALARY AS \"SALARY\",EMP_ADDRESS AS \"ADDRESS.EMP_ADDRESS\", EMP_PHONE AS \"ADDRESS.OTHERS.EMP_PHONE\", EMP_CITY AS \"ADDRESS.OTHERS.EMP_CITY\" FROM TBLEMPLOYEES FOR JSON PATH, ROOT('TBLEMPLOYEES')";
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var conn = new SqlConnection("Server=localhost\\SQLEXPRESS01;Database=Sample_2018;Trusted_Connection=True;");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\Output\TestJson.json");
file.WriteLine(jsonResult.ToString());
Please let me know correct procedure to output JSON data (with same format) from database table to a JSON file.