0

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);
    }
}
2
  • 1
    If you use dynamic you're throwing away compile time type safety. I would think long and hard before concluding that is in your best long term interests (especially in terms of maintainability). Personally I think what you have, while perhaps verbose, is clean, straightforward, and will help catch breaking changes in your JSON schema. Commented Mar 21, 2022 at 20:56
  • To fix your specific error, either DeserializeObject<List<ExpandoObject>> or add an enclosing property to the array such as {"weathers": ... JSON1 ...}. Commented Mar 21, 2022 at 21:21

2 Answers 2

1

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Ragavendra What are you talking about? These are my suggestions for THelpGuy. I am sorry but I don' t understand why are trying .
0

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

]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.