Reputation: 21
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?
Upvotes: 1
Views: 695
Reputation: 160
Your Item class does not match the JSON datastructure. You are missing that food is a List of Objects in the JSON structure. Your Item class only represents the Object right now. It also misses that rules is a List too.
Try:
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; }
}
You would also need to change Item to Root like this:
Root item = JsonConvert.DeserializeObject<Root>(jsonString);
Then you should find fruit like this:
Console.WriteLine($"Fruit:" + item.food[0].fruit);
Upvotes: 0
Reputation: 171
The item class doesnt match to your json, here is my suggest for this case:
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 FoodList
{
public List<Food> food { get; set; }
}
I created a button to make this convert
private void btnConvert_Click(object sender, EventArgs e)
{
string fileName = "YOUR_PATH\\test.json";
string jsonString = File.ReadAllText(fileName);
FoodList l = JsonConvert.DeserializeObject<FoodList>(jsonString);
tbResult.Text = $"Fruit:" + l.food[0].fruit;
}
Upvotes: 1
Reputation: 639
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; }
}
You can use this to quickly generate fitting models in C# from JSON data.
Upvotes: 1