public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append(\"[\");
if (o.HasRows)
while (o.Read())
s.App
If you want something that'll convert to arbitrary JSON, you could convert by serializing it into a Dictionary(Of string, object) thusly:
public IEnumerable<Dictionary<string, object>> Serialize(SqlDataReader reader)
{
var results = new List<Dictionary<string, object>>();
var cols = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
cols.Add(reader.GetName(i));
while (reader.Read())
results.Add(SerializeRow(cols, reader));
return results;
}
private Dictionary<string, object> SerializeRow(IEnumerable<string> cols,
SqlDataReader reader) {
var result = new Dictionary<string, object>();
foreach (var col in cols)
result.Add(col, reader[col]);
return result;
}
And then use the NewtonSoft.Json JsonConvert object to get your JSON:
var r = Serialize(reader);
string json = JsonConvert.SerializeObject(r, Formatting.Indented);
UPDATE: If you just want to use built-in methods, and you happen to be using MVC, you can use the built in Json helper method on your newly serialized :
JsonResult Index(int id) {
var r = Serialize(reader);
return Json(r, JsonRequestBehavior.AllowGet);
}
Try this:
o = cmd.ExecuteReader();
var dataQuery = from d in o.Cast<DbDataRecord>()
select new
{
Id = (String)d["Id"],
CN = (String)d["CatName"],
Ord = (String)d["Ord"],
Icon = (String)d["Icon"]
};
var data = dataQuery.ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
String jsonData = serializer.Serialize(data);
With Cinchoo ETL - an open source library, you can export SqlDataReader to JSON easily with few lines of code
string connectionstring = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
StringBuilder sb = new StringBuilder();
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
var comm = new SqlCommand("SELECT top 2 * FROM Customers", conn);
using (var parser = new ChoJSONWriter(sb))
parser.Write(comm.ExecuteReader());
}
Console.WriteLine(sb.ToString());
Output:
[
{
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"Address": "Obere Str. 57",
"City": "Berlin",
"Region": {},
"PostalCode": "12209",
"Country": "Germany",
"Phone": "030-0074321",
"Fax": "030-0076545"
},
{
"CustomerID": "ANATR",
"CompanyName": "Ana Trujillo Emparedados y helados",
"ContactName": "Ana Trujillo",
"ContactTitle": "Owner",
"Address": "Avda. de la Constitución 2222",
"City": "México D.F.",
"Region": {},
"PostalCode": "05021",
"Country": "Mexico",
"Phone": "(5) 555-4729",
"Fax": "(5) 555-3745"
}
]
This should do the job
private String sqlDatoToJson(SqlDataReader dataReader)
{
var dataTable = new DataTable();
dataTable.Load(dataReader);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dataTable);
return JSONString;
}
This is to enhance Chandu's Linq answer that uses query syntax (from ... select ...). If you prefer Method Syntax, here is your answer.
drdr = cmd.ExecuteReader();
Record[] recs = drdr.Cast<DbDataRecord>().Select( data=>new Record{
GraphID=(drdr.IsDBNull(0) ? "" : (string)data["LabelX"])
, XAxis=(drdr.IsDBNull(1) ? "1999-09-09 00:00:00" : Convert.ToDateTime(data["XDate"]).ToString("yyyy-MM-dd HH:mm:ss"))
, YVal=(drdr.IsDBNull(2) ? 0 : int.Parse(data["YFreq"].ToString()))
}).ToArray();
MemoryStream mem = new MemoryStream();
DataContractJsonSerializer szr = new DataContractJsonSerializer(typeof(Record[]));
szr.WriteObject(mem, recs);
String jsonData = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
Hope it helps somebody.
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<string> toJSON(this SqlDataReader reader)
{
var results = await reader.GetSerialized();
return JsonConvert.SerializeObject(results, Formatting.Indented);
}
public async static Task<IEnumerable<Dictionary<string, object>>> GetSerialized(this SqlDataReader reader)
{
var results = new List<Dictionary<string, object>>();
var cols = new List<string>();
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<string, object> SerializeRow(IEnumerable<string> cols,
SqlDataReader reader)
{
var result = new Dictionary<string, object>();
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.