Home > Back-end >  Create dynamic class and data table from json input in C#
Create dynamic class and data table from json input in C#

Time:03-22

Is it possible to create dynamic C# class from a JSON input file. I'm trying to re-write my code as we will have to import lots of JSON files from different vendors and would like to make the code repeatable and reusable.

Please find JSON sample below.

JSON1:

[{
"date":1647820800,
"humidity":75.72,
"pressure":1018.67,
"windspeed":3.88
},
{
"date":1647907200,
"humidity":75.35,
"pressure":1018.73,
"windspeed":4.47
}
]

C# Class1:

public class Weather
{
    public int date { get; set; }
    public double humidity { get; set; }
    public double pressure { get; set; }
    public double windspeed { get; set; }
}

JSON2:

[{
      "Id": 1,
      "productname": "item1",
      "supplier": "abc inc",
      "quantity": 500,
      "unitcost": "$12.37"
    }, 
    {
      "Id": 2,
      "productname": "Mountain Juniperus ashei",
      "supplier": "def. co.",
      "quantity": 100,
      "unitcost": "$9.78"
    }
]

C# Class2:

public class Supplier
{
    public int Id { get; set; }
    public string productname { get; set; }
    public string supplier { get; set; }
    public int quantity { get; set; }
    public string unitcost { get; set; }
}

I'm using Nwtonsoft JSON to deserialize data.

string jsonFile = "JSON1.json";
dynamic json = JsonConvert.DeserializeObject<ExpandoObject>(jsonFile, new ExpandoObjectConverter());

Error:

Unable to cast object of type 'System.Collections.Generic.List'[System.Object]' to type 'System.Dynamic.ExpandoObject'

Also, trying to make the use of DataTable dynamic as well irrespective of which JSON file is used.

DataTable:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("date", typeof(int)));
dt.Columns.Add(new DataColumn("humidity", typeof(double)));
dt.Columns.Add(new DataColumn("pressure", typeof(double)));
dt.Columns.Add(new DataColumn("windspeed", typeof(double)));

DataRow dr = dt.NewRow();

for (int i = 0; i < json.weather.Count; i  )
{
    {
        dr = dt.NewRow();
        dr["date"] = json.weather[i].date;
        dr["humidity"] = json.weather[i].humidity;
        dr["pressure"] = json.weather[i].pressure;
        dr["windspeed"] = json.weather[i].windspeed;
        dt.Rows.Add(dr);
    }
}

CodePudding user response:

you don't neeed any classes to create DataTable

var json= @"[{
""date"":1647820800,
""humidity"":75.72,
""pressure"":1018.67,
""windspeed"":3.88
},
{
""date"":1647907200,
""humidity"":75.35,
""pressure"":1018.73,
""windspeed"":4.47
}
]"; 

DataTable datatable=JsonConvert.DeserializeObject<DataTable>(json);

this is supllier list

List<Supplier> suppliers =JsonConvert.DeserializeObject<List<Supplier>>(json);

class

public partial class Supplier
{
    [JsonProperty("Id")]
    public long Id { get; set; }

    [JsonProperty("productname")]
    public string Productname { get; set; }

    [JsonProperty("supplier")]
    public string SupplierName { get; set; }

    [JsonProperty("quantity")]
    public long Quantity { get; set; }

    [JsonProperty("unitcost")]
    public string Unitcost { get; set; }
}

CodePudding user response:

You should try using the JObject type in the Newtonsoft.Json.Linq like below if you do not like to create class to deserialize for each json response

using Newtonsoft.Json.Linq;

string content = await response.Content.ReadAsStringAsync();

JObject resp = JObject.Parse(content);

Console.WriteLine(resp);
Console.WriteLine(resp["id"]);
Console.WriteLine(resp["name"]);

Your response is a List of json objects, so you should do like below to deserialize it and not get the conversion type error like you got.

var suppliers = JsonConvert.DeserializeObject<List<Supplier>>respo.response);
//JObject resp = JObject.Parse(content);

foreach (var supplier in suppliers)
    Console.WriteLine(supplier["productname "]);

]

  • Related