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.
Related
I am new here and actually very new to c#.
In a nutshell, I am using c# via Visual Studio, I am calling a data from a database and I want to save these data in a .csv file. The problem now is that I want to save these data on two columns at the same time.
My code do write them in a file but shifted not on the right rows.
Dictionary<string, string> elementNames = new Dictionary<string, string>();
Dictionary<string, string> elementTypes = new Dictionary<string, string>();
var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);
Dictionary<string, string> nodeResults = new Dictionary<string, string>();
Dictionary<string, string> nodeResults1 = new Dictionary<string, string>();
foreach (var nodename in elementNames.Values)
{
var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
var Uvolt = GetXMLAttribute(nodeRes, "U");
nodeResults.Add(nodename, Uvolt);
var Upercentage = GetXMLAttribute(nodeRes, "Up");
nodeResults1.Add(nodename, Upercentage);
StringBuilder strBldr = new StringBuilder();
string outputFile = #"C:\Users\12.csv";
string separator = ",";
foreach (var res in nodeResults)
{
strBldr.AppendLine($"{res.Key}{separator}{res.Value}");
}
foreach (var res1 in nodeResults1)
{
strBldr.AppendLine($"{separator}{separator}{res1.Value}");
}
File.WriteAllText(outputFile, strBldr.ToString());
}
this is the output of the previous code:
https://ibb.co/T4trQC3
I want these shifted values to move up beside the other values like that:
https://ibb.co/4S25v0h
Thank you
if you look to the code you are using AppendLine
strBldr.AppendLine($"{separator}{separator}{res1.Value}");
and if you want to append on same line just use Append
strBldr.Append($"{separator}{separator}{res1.Value}");
EDITED:
in linq you can use Zip function to zip to lists
// using System.Linq;
var results = Results.Zip(Results1, (firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);
Edit Full example
public static IDictionary<string, string> Results { get; set; }
public static IDictionary<string, string> Results1 { get; set; }
private static void Main(string[] args)
{
StringBuilder strBldr = new StringBuilder();
string outputFile = #"D:\12.csv";
Results = new Dictionary<string, string>()
{
{"N1", "20"},
{"N2", "0.399992"},
{"N3", "0.369442"},
{"N4", "0.369976"}
};
Results1 = new Dictionary<string, string>()
{
{"N1", "100"},
{"N2", "99.9805"},
{"N3", "92.36053"},
{"N4", "92.49407"}
};
IEnumerable<string> results = Results.Zip(Results1,
(firstList, secondList) => firstList.Key + "," + firstList.Value + "," + secondList.Value);
foreach (string res1 in results)
{
strBldr.AppendLine(res1);
}
File.WriteAllText(outputFile, strBldr.ToString());
}
for faster code you can try this
HashSet<Tuple<string, string, string>> values = new HashSet<Tuple<string, string, string>>();
var nodes = webservice.nepService.GetAllElementsOfElementType(webservice.ext, "Busbar", ref elementNames, ref elementTypes);
foreach (var nodename in elementNames.Values)
{
var nodeRes = webservice.nepService.GetResultElementByName(webservice.ext, nodename, "Busbar", -1, "LoadFlow", null);
var Uvolt = GetXMLAttribute(nodeRes, "U");
var Upercentage = GetXMLAttribute(nodeRes, "Up");
values.Add(Tuple.Create(nodename, Uvolt, Upercentage));
}
var output = string.Join("\n", values.ToList().Select(tuple => $"{tuple.Item1},{tuple.Item2},{tuple.Item3}").ToList());
string outputFile = #"C:\Users\12.csv";
File.WriteAllText(outputFile, output);
if the rowCount for Results and Results1 are same and the keys are in the same order, try:
for (int i = 0; i < Results.Count; i++)
strBldr.AppendLine($"{Results[i].Key}{separator}{Results[i].Value}{separator}{Results1[i].Value}");
Or, if the rows are not in the same order, try:
foreach (var res in Results)
strBldr.AppendLine($"{res.Key}{separator}{res.Value}{separator}{Results1.Single(x => x.Key == res.Key).Value}");
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);
}
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;
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);
}
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;
}