public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append(\"[\");
if (o.HasRows)
while (o.Read())
s.App
Since SQL Server 2016, Microsoft embedded this feature with sql queries. You can achieve it by using FOR JSON
keyword at the end of your queries.
select * from table_example where somecolumn = somecondition FOR JSON AUTO
for more details and example you can go through this official documents Format JSON Output Automatically with AUTO Mode (SQL Server)
Here is the C# code example from Microsoft to get JSON string from SQL queries.
var queryWithForJson = "SELECT ... FOR JSON";
var conn = new SqlConnection("");
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());
}
}
Warning: This solution is only valid for SQL SERVER 2016 and higher.