public string toJSON(SqlDataReader o)
{
StringBuilder s = new StringBuilder();
s.Append(\"[\");
if (o.HasRows)
while (o.Read())
s.App
add reference : System.Web.Extensions
to project
then
using System.Web.Script.Serialization;
in c# code, you can use write :
var json = new JavaScriptSerializer().Serialize(obj);
I use this code, based on Jonathan's answer:
private IEnumerable<Dictionary<string, object>> ConvertToDictionary(IDataReader reader)
{
var columns = new List<string>();
var rows = new List<Dictionary<string, object>>();
for (var i = 0; i < reader.FieldCount; i++)
{
columns.Add(reader.GetName(i));
}
while (reader.Read())
{
rows.Add(columns.ToDictionary(column => column, column => reader[column]));
}
return rows;
}
And then:
var rows = this.ConvertToDictionary(reader);
return JsonConvert.SerializeObject(rows, Formatting.Indented);
This can't be that hard. This is what I've done when I want to return search results to a web page as JSON.
First, have a class like this
public class SearchResult
{
public string model_no { get; set; }
public string result_text { get; set; }
public string url { get; set; }
public string image_url { get; set; }
}
and then have the code below.
string sql_text = "select * from product_master where model_no like @search_string and active=1";
SqlConnection connection = new SqlConnection(sql_constr);
SqlCommand cmd = new SqlCommand(sql_text, connection);
cmd.Parameters.AddWithValue("@search_string", "%" + search_string + "%");
connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
List<SearchResult> searchresults = new List<SearchResult>();
while (rdr.Read())
{
SearchResult sr = new SearchResult();
sr.model_no = rdr["model_no"].ToString();
sr.result_text = rdr["product_name"].ToString();
sr.url = rdr["url_key"].ToString();
searchresults.Add(sr);
}
connection.Close();
//build json result
return Json(searchresults, JsonRequestBehavior.AllowGet);
this works for me very well..
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("<connection string>");
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.
Another option would be to use James Newton-King's excellent JSON.NET library - http://www.newtonsoft.com/json
Here's a quick example on how to use it to build up a collection and then output it as a JSON-serialized string:
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
ArrayList objs = new ArrayList();
//get the data reader, etc.
while(o.Read())
{
objs.Add(new
{
Id = o["Id"],
CN = o["CatName"],
Ord = o["Ord"],
Icon = o["Icon"]
});
}
//clean up datareader
Console.WriteLine(JsonConvert.SerializeObject(objs));
Console.ReadLine();
}
}
You could do the same with your looping by reading in each row of your SqlDataReader into an anonymous object and then use JSON.NET to serialize it to a string.
Hope this helps!
I made the following method where it converts any DataReader to JSON, but only for single depth serialization:
you should pass the reader, and the column names as a string array, for example:
String [] columns = {"CustomerID", "CustomerName", "CustomerDOB"};
then call the method
public static String json_encode(IDataReader reader, String[] columns)
{
int length = columns.Length;
String res = "{";
while (reader.Read())
{
res += "{";
for (int i = 0; i < length; i++)
{
res += "\"" + columns[i] + "\":\"" + reader[columns[i]].ToString() + "\"";
if (i < length - 1)
res += ",";
}
res += "}";
}
res += "}";
return res;
}