DataTable to nested JSON using Javascript serializer in C# - c#

I'm converting a Data Table rows into a JSON string. Using a Javascript serializer I have generated a normal JSON string. How can we generated it as Nested string.
Current Json output
{
"PatientId":"32424",
"CustomerId":"XXXX",
"Name":"DiastolicBloodPressure",
"Value":89,
"Unit":"mmHg",
"MinValue":50,
"MaxValue":90,
"SessionElementResponseText":null
}
Expected
{
"PatientId":"32424",
"CustomerId":"XXXX",
"VitalThreshold":{
"Name":"DiastolicBloodPressure",
"Value":89,
"Unit":"mmHg",
"MinValue":50,
"MaxValue":90
},
"SessionElementResponseText":null
}
Code
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach(DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach(DataColumn col in table.Columns)
{
if(col.ColumnName.Equals("Name"))
{
//Trying here
}
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize(rows);
}

public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
string[] keys = new string[] { "Name", "Value", "Unit", "MinValue", "MaxValue" };
foreach(DataRow dr in table.Rows)
{
Dictionary<string, object> row = new Dictionary<string, object>();
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach(DataColumn col in table.Columns)
{
if(keys.Contains(col.ColumnName)) dict.Add(col.ColumnName, dr[col]);
else row.Add(col.ColumnName, dr[col]);
}
row.Add("VitalThreshold", dict);
rows.Add(row);
}
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize(rows);
}

Basically, you have to add one condition to buffer the inner row. Then, at the end of the loop add the "inner row" into the main row.
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
var innerList = new string[] { "Name", "Value", "Unit", "MinValue", "MaxValue" };
var innerRow = new Dictionary<string, object>();
foreach (DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
if (innerList.Contains(col.ColumnName))
{
innerRow.Add(col.ColumnName, dr[col]);
}
else
{
row.Add(col.ColumnName, dr[col]);
}
}
row.Add("VitalThreshold", innerRow);
rows.Add(row);
}
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize(rows);
}

Related

Remove and replace column names DataTable c#

I have a DataTable like this:
DataTable dataTable = new DataTable();
dataTable.Columns.Add("A", typeof(string));
dataTable.Columns.Add("B", typeof(string));
dataTable.Columns.Add("C", typeof(string));
List<string> headersToSkip = new List<string>() { "A", "B" };
Dictionary<string, string> headersToReplace = new Dictionary<string, string>() { { "C", "D" } };
IEnumerable<DataColumn> queriableColumms = dataTable.Columns.Cast<DataColumn>().AsQueryable().ToList();
var toBeRemoved = from DataColumn column in queriableColumms
where headersToSkip != null && headersToSkip.Contains(column.ColumnName)
select column;
foreach (DataColumn column in toBeRemoved)
{
dataTable.Columns.Remove(column);
}
if (headersToReplace != null)
{
foreach (KeyValuePair<string, string> kvp in headersToReplace)
{
foreach (DataColumn column in dataTable.Columns.Cast<DataColumn>().AsQueryable().ToList())
{
if (column.ColumnName.Equals(kvp.Key))
column.ColumnName = kvp.Value;
}
}
}
Is it possible to remove columns in DataTable and replace column names with some other column names efficiently.
By efficiently, if you mean with less code, you could do the following.
To Remove Columns
List<string> headersToSkip = new List<string>() { "A", "B" };
foreach(var header in headersToSkip)
{
dataTable.Columns.Remove(header);
}
To Rename Columns,
Dictionary<string, string> headersToReplace = new Dictionary<string, string>() { { "C", "D" } };
foreach(var header in headersToReplace)
{
dataTable.Columns[header.Key].ColumnName = header.Value;
}

exclude an object from getting serialized

ds.Tables.Add(dt);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in ds.Tables[0].Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in ds.Tables[0].Columns)
{
childRow.Add(col.ColumnName, row[col].ToString().Replace("\r\n", " ").Replace(":", " ").Replace("\t", " ").Replace("/", " "));
}
parentRow.Add(childRow);
}
Jrep.status = "S";
Jrep.result = jsSerializer.Serialize(parentRow);
Jrep.err_code = "";
Jrep.err_desc = "";
Jrep.Input = new Input { cabc= abc, cdbc= dbc, };
result = JsonConvert.SerializeObject(Jrep);
This is the code where I am serializing the dataset into json string.the next step would be to assign the json string to a member of the class and serialize the class but I dont want the already serialized object to again serialize.how can i stop this.Any suggestions appreciated.Thank you.

How to covert a DataTable to Json Format? [duplicate]

This question already has answers here:
Convert datatable to JSON in C#
(18 answers)
Closed 6 years ago.
I am trying to convert the DataTable that I have fetched from the database to Json format. But I am getting an error.
public string ConvertTableToJSON(DataTable objDataTable)
{
ArrayList columnNames = new ArrayList();
int rowCount = objDataTable.Rows.Count;
int currentRow = 1;
string json = "";
//fetching column names
foreach (DataColumn objColumn in objDataTable.Columns)
{
columnNames.Add(objColumn.ColumnName);
}
//generating json string for each row
foreach (DataRow objRow in objDataTable.Rows)
{
json = json + "{";
json = json + ConvertRowToJSON(objRow, columnNames);
json = json + "}";
if (currentRow != rowCount)
{
json = json + ",";
}
currentRow = currentRow + 1;
}
return json;
}
The above is the code for the conversion of the DataTable to Json format.
" Index was outside the bounds of the array. " is the error when debugging the code. This error occurs in the line
if (data[0] == '[' || data[0] == '{')
This method is used to convert datatable to json string
public string ConvertDataTabletoJSON(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
It uses System.Web.Script.Serialization.JavaScriptSerializer to serialize the contents to JSON format:
You can Convert DataTable to JSON using JavaScriptSerializer by using following code
public string DataTableToJsonWithJavaScriptSerializer(DataTable objDataTable)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in objDataTable.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
You can use Json.Net DLL and convert datatable to json like
public string DataTableToJsonWithJsonNet(DataTable objDataTable)
{
string jsonString=string.Empty;
jsonString = JsonConvert.SerializeObject(objDataTable);
return jsonString;
}
Include library.
Newtonsoft.Json;

Very Big JSON (92,000 rows) does not load

I have a simple function to return my datatable as JSON from c# using the Serializer as follows -
public static string ConvertToJSON (DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
Which I use as follows
return ConvertToJSON(objDataTable);
where objDataTable is my Datatable
I also have
return JsonConvert.SerializeObject(strArrMapObject, Formatting.None);
where I am using the library Newtonsoft.Json and strArrMapObject is an Itemarray built from objDataTable
Both the above methods work fine for small datatables and I get the output like this -
["11-06-2014 00:00:00","17:45:00","Beta","357637031475680","404490480844084","78","IN","","8143888569","48"]
But when I do it for a big datatable (eg. 92,000 rows), nothing happens!
There is no response and there is no timeout error also.
So when I use
alert (response);
[in Javascript] or even
document.getElementById('divDataHolder').innerHTML = response;
[in Javascript]
absolutely nothing happens!
Please help!
Rewrite your request so that you can ask
select 100 rows page 1 // selects items 1-100
select 100 rows page 2 // selects items 101-200
This would solve more then 1 problem.
public static string ConvertToJSON (DataTable dt, int page = 0, int count = 100)
//...
foreach (DataRow o in dt.AsEnumerable().Skip(page * count).Take(count))
Edit: You can use following method to get Json
//add reference System.Data
//add reference System.Web.extensions
//add reference System.Web.DataTableExtensions
public static string ConvertToJson(DataTable dt, int page = 0, int count = 100)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var rows = new List<Dictionary<string, object>>();
foreach (DataRow dr in dt.AsEnumerable().Skip(page * count).Take(count).ToList())
{
rows.Add(dt.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => dr[col]));
}
return serializer.Serialize(rows);
}

DataTable to nested json in c#

I want to convert a DataTable to nested JSON. I have a table Announcement with column name Category, Headline, Details, Short_desc, Author and Display_date.
Datatabel result is like:
Category Headline Details Short_desc Author Display_date
Sports H1 d1 sd1 a1 dd1
Sports h2 d2 sd2 a2 dd2
Technology t1 d3 sd3 a3 dd3
Technology t2 d4 sd4 a4 dd4
Now I want JSON result something like:
{
"Sports" : [ [
"Headline":"H1",
"Details":"d1",
"Short_desc":"sd1",
"Author":"a1",
"Display_date":"dd1"
],
[ "Headline":"H2",
"Details":"d2",
"Short_desc":"sd2",
"Author":"a2",
"Display_date":"dd2"
]
],
"Technology" : [ [
"Headline":"t1",
"Details":"d3",
"Short_desc":"sd3",
"Author":"a3",
"Display_date":"dd3"
],
[ "Headline":"t4",
"Details":"d4",
"Short_desc":"sd4",
"Author":"a4",
"Display_date":"dd4"
]
]
}
I used the following code:
DataTable dts = get_banner_detail_service("");
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dts.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dts.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
Response.Write(serializer.Serialize(rows));
Response.Flush();
Response.End();
Result of above code is not like what I expected. It is like:
{
"Sports" : [
"Headline":"H1",
"Details":"d1",
"Short_desc":"sd1",
"Author":"a1",
"Display_date":"dd1"
],
"Sports" :[
"Headline":"H2",
"Details":"d2",
"Short_desc":"sd2",
"Author":"a2",
"Display_date":"dd2"
] ....
}
HI Finally i solve the issue ...
below is the updated code -
DataTable dts = get_banner_detail_service("");
DataTable dtc = get_banner_detail_cat("");
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> rowss;
Dictionary<string, object> rowsc;
List<object> rowsin;
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
rowsc = new Dictionary<string, object>();
foreach (DataRow dr in dtc.Rows)
{
string cat = dr["Category"].ToString();
var filteredAndroid = (from n in dts.AsEnumerable()
where n.Field<string>("Category").Contains(cat)
select n).ToList();
if (filteredAndroid.Count != 0)
{
DataTable t = filteredAndroid.CopyToDataTable();
t.Columns.Remove("Category");
rowss = new Dictionary<string, object>();
rowsin = new List<object>();
foreach (DataRow drr in t.Rows)
{
foreach (DataColumn col in t.Columns)
{
rowss.Add(col.ColumnName, drr[col]);
}
rowsin.Add(rowss);
rowss = new Dictionary<string, object>();
}
rowsc.Add(cat, rowsin);
t.Dispose();
t = null;
filteredAndroid = null;
}
}
rows.Add(rowsc);
string json = JsonConvert.SerializeObject(rows, Newtonsoft.Json.Formatting.Indented);
if (json.Length > 2)
{
json = json.Substring(1, json.Length - 2);
}
Response.Write(json);
Response.Flush();
Response.End();
You need to create nested dictionary as:
Dictionary<string, Dictionary<string, object>> rows = new Dictionary<string, Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dts.Rows)
{
row = new Dictionary<string, object>();
var columns = dts.Columns;
for (int i = 1; i < columns.Count; i++)
{
row.Add(columns[i].ColumnName, dr[columns[i]]);
}
if (rows.ContainsKey(columns[0].ColumnName))
rows[columns[0].ColumnName] = rows[columns[0].ColumnName].Concat(row).ToDictionary(p=>p.Key,v=>v.Value);
else
rows[columns[0].ColumnName] = row;
}

Categories