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!