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);
}
}
DeserializeObject<List<ExpandoObject>>or add an enclosing property to the array such as{"weathers": ... JSON1 ...}.