How to covert a DataTable to Json Format? [duplicate] - c#

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;

Related

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

How to get keys and values of .json file which is generated by parser dynamically in c#

We have following scenario,
We need to parse resumes of candidates and i am using below parser to parse resume in Json format, right.
https://github.com/antonydeepak/ResumeParser
and Json files which i get are in valid format as i checked them in online jsonviewer, but it is cleared that each resume is in different format. so each time parser introduced new pair of Keys ,
Example 1.
Example 2.
Above two formats are of two different resumes and so on...
so now i need to iterate through every key and value that are dynamically generated.
as for as i did to get JObject and JArray at level 0, now i need to iterate through each JObject and JArray to get its values.
I used Json.net to get them
string text = System.IO.File.ReadAllText(#"C:\abc.json");
var d = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(text);
and it showed me data as
abc.json has JObjects and JArray, so now i need to iterate through each and every line and need to get every key and value from parsed json file and load it to datatable and tried it using google , but it missed some of keys and values.
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Key", typeof(string));
dt.Columns.Add("Value", typeof(string));
string text = System.IO.File.ReadAllText(#"C:\antony_thomas.json");
var d = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(text);
foreach (var item in d)
{
var key = "";
var val = item.Value;
if (val is JObject)
{
dynamic dynObj = JsonConvert.DeserializeObject(Convert.ToString(val));
foreach (var ite in dynObj)
{
DataRow row = dt.NewRow();
string jsonvalue = Convert.ToString(ite).Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace("\"", "");
string jkey = jsonvalue.Split(':')[0];
string jval = jsonvalue.Split(':')[1];
row["Key"] = jkey;
row["Value"] = jval;
dt.Rows.Add(row);
}
// key = item.Key;
}
if (val is JArray)
{
//key = item.Key;
foreach (var it in val)
{
// var newkey=
DataRow row = dt.NewRow();
string jsonvalue = Convert.ToString(it).Replace("[", "").Replace("]", "").Replace("{", "").Replace("}", "").Replace("\"", "");
//Convert.ToString(test);
string jkey = jsonvalue.Split(':')[0];
string jval = jsonvalue.Split(':')[1];
row["Key"] = jkey;
row["Value"] = jval;
dt.Rows.Add(row);
}
}
}
I am using asp.net , C#, Json.net , if anyone have any idea so please guide me how can i get my desired result..
I used this code recently to traverse an arbitrary JSON string.
Each element is dumped with a row of dots at the beginning indicating its level in the hierarchy.
You could modify it to output to a DataTable as you walk through an JArray for example.
public static void JsonFileDump(string path)
{
//Parse the data
string jsonStr = File.ReadAllText(path);
JToken token = JToken.Parse(jsonStr); // get parent token
JsonTokenDump(token);
}
public static void JsonTokenDump(JToken node, int lvl = 0, string nodeName = null)
{
if (nodeName != null)
Console.WriteLine("{0}Node Name={1}, Type={2}", new string('.', lvl), nodeName, node.Type);
else
Console.WriteLine("{0}Node Type={1}", new string('.', lvl), node.Type);
if (node.Type == JTokenType.Object)
{
foreach (JProperty child in node.Children<JProperty>())
{
JsonTokenDump(child.Value, lvl + 1, child.Name);
}
}
else if (node.Type == JTokenType.Array)
{
foreach (JToken child in node.Children())
{
JsonTokenDump(child, lvl + 1);
}
}
}

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.

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