Qjimbo
Qjimbo

Reputation: 377

Build table programmatically for export to/import from JSON?

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!

Upvotes: 3

Views: 312

Answers (3)

alan
alan

Reputation: 6943

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

Upvotes: 3

ivamax9
ivamax9

Reputation: 2629

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)

Upvotes: 1

Sayan Pal
Sayan Pal

Reputation: 4956

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.

Upvotes: 0

Related Questions