public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append(\"[\");
if (o.HasRows)
while (o.Read())
s.App
Further to Jonathan's Answer, I had a similar requirement in ASP.NET Core to convert the result of an SQLDataReader to a JSON string or a Result Object, so I created an extension method for it as :
public static class MyExtensions
{
public async static Task toJSON(this SqlDataReader reader)
{
var results = await reader.GetSerialized();
return JsonConvert.SerializeObject(results, Formatting.Indented);
}
public async static Task>> GetSerialized(this SqlDataReader reader)
{
var results = new List>();
var cols = new List();
for (var i = 0; i < reader.FieldCount; i++)
cols.Add(reader.GetName(i));
while (await reader.ReadAsync())
results.Add(SerializeRow(cols, reader));
return results;
}
private static Dictionary SerializeRow(IEnumerable cols,
SqlDataReader reader)
{
var result = new Dictionary();
foreach (var col in cols)
result.Add(col, reader[col]);
return result;
}
}
& used it as per my requirement as :
var result = await reader.GetSerialized(); //to get the result object
or
string strResult = await reader.toJSON(); //to get the result string
I created an async method because I had some other things to be done till the reading was finished from database.