I have a Product class:
class Product
{
public string Name;
}
A Product List class:
class ProductDataFile
{
public List<Product>? products;
}
And a class for loading json into these classes:
public void LoadProducts()
{
string jsonString = File.ReadAllText(FileLoc);
ProductDataFile? productDataFile= JsonSerializer.Deserialize<ProductDataFile>(jsonString);
var ProductName = productDataFile.products.First().Name;
}
This throws a "System.ArgumentNullException: Value cannot be null. (Parameter 'source')". I used the debugger and products is null, so that seems to be the problem.
My Json looks something like this:
{
"listOfProducts": "List of products",
"products": [
{
"Name": "product one"
}
]
}
```
CodePudding user response:
The library Newtonsoft.json
method of JsonSerializer.Deserialize
need to use properties instead of fields, otherwise you might not Deserialize
anything from your JSON data.
class Product
{
public string Name {get;set;}
}
class ProductDataFile
{
public List<Product>? products {get;set;}
}
I would suggest you use json2csharp, it can easy to get the model by JSON
and make sure it will be work.