I have to read a JSON file that is stored locally in my machine but it gives me empty data when I try to access a specific item.
Here's my JSON file structure:
{
"food": [
{
"id": "8a7f65c47cdb33f4017d08fff1fe3cee",
"rules": [
],
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
]
}
Here's what I have tried:
//test.json is the name of my file
string fileName = "test.json";
string jsonString = File.ReadAllText(fileName);
Item item = JsonConvert.DeserializeObject<Item>(jsonString);
//here I want to print out the fruit "Apple" but it gives me null;
Console.WriteLine($"Fruit:" item.fruit);
Item class:
public class Item
{
public string fruit;
public string size;
public string color;
public string id;
public string rules;
}
PS: If I noticed that this code will work only if my data structure is without the "food" block, and it think that is the problem here. Any ideas on how can I fix this?
CodePudding user response:
The item class does not represent the correct structure for your JSON data. You have a root object which contains a property that is a list of another object.
To correctly deserialize your JSON data your class should look something like this:
public class Food
{
public string id { get; set; }
public List<object> rules { get; set; }
public string fruit { get; set; }
public string size { get; set; }
public string color { get; set; }
}
public class Root
{
public List<Food> food { get; set; }
}

