3

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!

Qjimbo
  • 377
  • 2
  • 11
  • 1
    Create a class with your columns and then create list of them. It will be serialize in json as you want. Profit! – ivamax9 Oct 01 '15 at 20:01
  • @Chase he need to add columns dynamically – Overmachine Oct 01 '15 at 20:02
  • can you provide the code of your datatable you were trying? – Overmachine Oct 01 '15 at 20:03
  • Have you looked into JSON.NET? It has a method specifically for the purpose of serializing a DataTable to JSON. – alan Oct 01 '15 at 20:13
  • Just because you have circular reference issue, it doesn't mean you should abandon `DataTable` as a way to add -remove columns. – T.S. Oct 01 '15 at 20:21
  • I have added the exact code I use which causes the error, even with JSON.NET I get this, any suggestions on how to avoid? – Qjimbo Oct 01 '15 at 21:07
  • Here is your answer http://stackoverflow.com/a/16279843/1704458 – T.S. Oct 01 '15 at 21:13
  • @T.S. Thanks so much - it worked! I have updated the question with the solution! – Qjimbo Oct 13 '15 at 18:00
  • Possible duplicate of [A circular reference was detected while serializing an object of type 'System.Reflection](http://stackoverflow.com/questions/16279442/a-circular-reference-was-detected-while-serializing-an-object-of-type-system-re) – T.S. Oct 13 '15 at 18:09

3 Answers3

3

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);
alan
  • 6,705
  • 9
  • 40
  • 70
  • 1
    I like this. This is easy – T.S. Oct 01 '15 at 20:22
  • Thanks for the advice, unfortunately I get the same error. This is the code I use to make the table: `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); return Content(json, "application/json");` – Qjimbo Oct 01 '15 at 21:02
  • 1
    @Qjimbo you need to resolve references in your project(s). It has nothing todo with how to use data table. And you need to post your code in your question, not in comments – T.S. Oct 01 '15 at 21:06
1

Like a variant your table can be stored like this:

public class TestClass
{
   public int Id { get; set; }
   public Dictionary<string,string> CR { get; set; } //Columns And Rows
}

And then create a list of this class, which represent your table : List<TestClass> and then serialize or deserialize it with custom converter.

P.S: alan idea is better)

ivamax9
  • 2,601
  • 24
  • 33
  • this is an idea but will require some extra coding for serialization. This is custom serialization – T.S. Oct 01 '15 at 20:19
0

Since you are importing/exporting this data to/from JSON, how about doing this on client side using JavaScript, though I am not sure whether that is at all an option for you or not. However, doing this gymnastic with JavaScript supports your requirement of adding col/properties dynamically, if that is what you need absolutely.

Otherwise having a simple C# class and constructing a list with that class' objects and then serializing the list should also do the job.

Sayan Pal
  • 4,768
  • 5
  • 43
  • 82