Home > OS >  Add nested properties to the existing class at runtime and export it to json as per below format
Add nested properties to the existing class at runtime and export it to json as per below format

Time:07-21

I need to fetch all the table names and their column names from database using an sql query in c# console application and export it to json. The problem is that i don't know what the table names and column names at compile time and i need to add them to the class as property on runtime. The json format should be below:- For example: Database name is mydatabase Tables names are tbl1,tbl2,tbl3 Column names are tbl1(tbl1Col1, tbl1col2), tbl2(tbl2Col1, tbl2col2),tbl3(tbl3Col1, tbl3col2)

Json format should be:

{
  "tables":{
      "tbl1":{
            "columns": {
                  "tbl1Col1":{},
                  "tbl1Col2":{},
            }    
  },
      "tbl2":{
              "columns": {
                  "tbl2Col1":{},
                  "tbl2Col2":{},
            }
  },
      "tbl3":{
             "columns": {
                  "tbl3Col1":{},
                  "tbl3Col2":{},
            }
  }
  }
}

CodePudding user response:

I do have a solution, I was just too tired (caffeine depraved) to notice it, just use a Dictionary, so

class Root // Whatever your class is called
{
    [JsonPropertyName("tables")]
    public Dictionary<string, Table> Tables { get; set; } = new();
}

class Table
{
    [JsonPropertyName("columns")]
    public Dictionary<string, Column> Columns { get; set; } = new();
}

class Column { }

You can then just JsonSerializer,Serialize(root) and it works and produces JSON in the correct structure you want. I created a small demo here to showcase it (don't be alarmed, you can construct your dictionaries however you want, I just used a lot of syntactic sugar)

CodePudding user response:

I think you can work with nested ExpandoObjects.

    [TestMethod]
    public void TestMethod1()
    {
        dynamic rootTables = new ExpandoObject();
        dynamic tables = new ExpandoObject();
        dynamic tbl1Col1 = new ExpandoObject();
        dynamic columns = new ExpandoObject();
        dynamic column = new ExpandoObject();


        AddProperty(column, "tbl1Col1", tbl1Col1);
        AddProperty(columns, "columns", column);
        AddProperty(tables, "tbl1",  columns);
        AddProperty(rootTables, "tables", tables);

        string json = JsonConvert.SerializeObject(rootTables);

        Assert.AreEqual("{\"tables\":{\"tbl1\":{\"columns\":{\"tbl1Col1\":{}}}}}", json);
    }


    public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
    {
        var expandoDict = expando as IDictionary<String, object>;
        if (expandoDict.ContainsKey(propertyName))
            expandoDict[propertyName] = propertyValue;
        else
            expandoDict.Add(propertyName, propertyValue);
    }
  •  Tags:  
  • c#
  • Related