How to show json objects(with diffrent data fileds) in a datatable?

İ want to show json objects in a datatable. (C#.MVC) Due fact that json object have mostly different fileds according machines data they belong. For each json object i dont want to write a seperate class. How can i handle this json objects dynamically and show datatable in a single class? Thanks in advance.

1 answer

  • answered 2020-03-31 22:09 RajN

    With Cinchoo ETL, an open source library, you can do it as follows

    string json = @"{
        ""header"": ""myheader"",
        ""transaction"": {
        ""date"": ""2019-09-24"",
        ""items"": [
            {
            ""number"": ""123"",
            ""unit"": ""EA"",
            ""qty"": 6
            },
            {
            ""number"": ""456"",
            ""unit"": ""CS"",
            ""qty"": 4
            }
        ]
        }
    }";
    
    using (var r = ChoJSONReader.LoadText(json))
    {
        var dt = r.Select(f => f.Flatten()).AsDataTable();
        Console.WriteLine(dt.DumpAsJson());
    }
    

    Output:

    [
      {
        "header": "myheader",
        "transaction_date": "2019-09-24",
        "transaction_items_0_number": "123",
        "transaction_items_0_unit": "EA",
        "transaction_items_0_qty": 6,
        "transaction_items_1_number": "456",
        "transaction_items_1_unit": "CS",
        "transaction_items_1_qty": 4
      }
    ]
    

    Hope it helps.