I'm trying to deserialize a JSON file to a c# class. However, my deserialize method always returns null. My JSON file looks like this-
{
"Products": [
{
"ProductID": 994,
"Name": "LL Bottom Bracket",
"ProductNumber": "BB-7421",
"ProductCategoryID": 9,
"ProductCategory": "Bottom Brackets",
"ProductModelID": 95,
"Description": "Chromoly steel."
},
{
"ProductID": 995,
"Name": "ML Bottom Bracket",
"ProductNumber": "BB-8107",
"ProductCategoryID": 9,
"ProductCategory": "Bottom Brackets",
"ProductModelID": 96,
"Description": "Aluminum alloy cups; large diameter spindle."
}
]
}
I'm trying to serialize it to below class-
public class Product
{
[JsonProperty("ProductID")]
public long ProductId { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ProductNumber")]
public string ProductNumber { get; set; }
[JsonProperty("ProductCategoryID")]
public long ProductCategoryId { get; set; }
[JsonProperty("ProductCategory")]
public string ProductCategory { get; set; }
[JsonProperty("ProductModelID")]
public long ProductModelId { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("Color", NullValueHandling = NullValueHandling.Ignore)]
public string Color { get; set; }
}
public partial class Products
{
[JsonProperty("Products")]
public IEnumerable<Product> ProductsProducts { get; set; }
}
And finally, I'm using this code to deserialize it, however it returns null for some reason. Can someone please help?
public Products Get()
{
var jsonString = IO.File.ReadAllText("ProductsData.json");
var products = JsonSerializer.Deserialize<Products>(jsonString);
return products;
}
IEnumerable<Product>for the"Products"property - try either making it anICollection<Product>orList<Product>, if that doesn't work. For a more elegant solution, I believe there's a way to set a default collection implementation but I don't know what it is off the top of my head.