DataTable to nested json in c# - 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;
}

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;
}

DataTable to nested JSON using Javascript serializer in 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);
}

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;

SQL Data to JSON C#

LIST Time Status
A 22:05 0
B 22:10 1
C 22:30 1
A 22:40 0
C 22:50 1
B 22:60 1
The above table needs to be converted to below JSON format
[
{ "name": "A",
data: [ [22:05,0],
[22:40,0]
]
},
{ "name": "B",
data: [ [22:10,1],
[22:60,1]
]
}
{ "name": "C",
data: [ [22:30,1],
[22:50,1]
]
}
]
The above is in a DataTable , now need to format the JSON,the below code does not give me in the same format.
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
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);
}
I would suggest reading the data from your table and creating a custom class to represent the data that needs to be serialized. You data would be represented in a class that looks like this:
public class MyType {
public string Name {get;set;}
public List<List<string>> Data {get;set;}
}
Then you would need a method to parse through your DataTable. Something like this might do it:
public List<MyType> ParseTable(DataTable dt) {
var myTypes = new List<MyType>();
var dictionary = new Dictionary<string, List<List<string>>>();
foreach(DataRow dr in dt.Rows) {
var name = dr[0];
var time = dr[1];
var status = dr[2];
if(!dictionary.ContainsKey(dr[0]) {
dictionary[name] = new List<List<string>>();
}
dictionary[name].Add(new List<string>{time, status});
}
foreach(var key = dictionary.Keys) {
myTypes.Add(new MyType {Name = key, Data = dictionary[key]});
}
return myTypes;
}
Then use a JSON serializer like http://james.newtonking.com/json to handle the actual serialization of your object into JSON.
That would look something like this:
public string Serialize(List<MyType> myTypes) {
return JsonConvert.SerializeObject(myTypes);
}
Please understand that this is freehand and off the cuff. So it may not be optimal and may need some tweaking. But this should get you where you are trying to go.

Categories