I am using EntityFramework, C# and MVC to build a web app. I need to create a dynamic table in RAM like this
COL1 | COL2 | COL3... etc.
1 | Val | Val
2 | Val | Val
I then need to be able to read/write it to JSON in the following format:
[
{id:1, COL1: "Val", COL2: "Val", COL3: "Val" },
{id:2, COL1: "Val", COL2: "Val", COL3: "Val" }
];
I need to be able to read and write the table to this format, dynamically add columns and rows easily.
I have tried using DataTable but that causes this error when it serializes:
Error: A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'.
Any recommendations would be appreciated.
EDIT: This is the code I used to build the table that causes the error, even when using JSON.NET serialization:
DataTable datatable = new DataTable();
datatable.Columns.Add("DBID");
datatable.Columns.Add("ROW");
datatable.Columns.Add("ID");
DataRow row = datatable.NewRow();
row["DBID"] = "Test";
row["ROW"] = "Test";
row["ID"] = "Test";
datatable.Rows.Add(row);
string json = JsonConvert.SerializeObject(datatable, Formatting.Indented); // <- Error here
return Content(json, "application/json");
EDIT 2 - SOLUTION:
string json = JsonConvert.SerializeObject(datatable, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.None
}
);
Thanks alan and T.S. for pointing me in the right direction and everyone else who answered!
As mentioned in many other posts, you can always add a reference to JSON.NET which exposes the method below:
var json = JsonConvert.SerializeObject(dataTableToConvertToJSON,
Formatting.Indented);
Update:
Try this code instead. It should take care of the error you're getting:
var dataTableToConvertToJSON = JsonConvert.SerializeObject(dataTableToConvertToJSON,
Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
To return the Json as a string use this:
return json;
To return a Json object use this:
return Json(dataTableToConvertToJSON, JsonRequestBehavior.AllowGet);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With