无法读取 JSON 个嵌套文件

Cannot read JSON nested file

我必须读取本地存储在我机器上的 JSON 文件,但当我尝试访问特定项目时它会给我空数据。

这是我的 JSON 文件结构:

{
    "food": [{
            "id": "8a7f65c47cdb33f4017d08fff1fe3cee",
            "rules": [

            ],

            "fruit": "Apple",
            "size": "Large",
            "color": "Red"
        }
    ]
}

这是我尝试过的方法:

//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);

项目class:

public class Item
{
    public string fruit;
    public string size;
    public string color;
    public string id;
    public string rules;
}

PS:如果我注意到此代码仅在我的数据结构没有“食物”块时才有效,并且它认为这就是问题所在。 关于如何解决此问题的任何想法?

项目 class 不代表您的 JSON 数据的正确结构。 您有一个包含 属性 的根对象,它是另一个对象的列表。

要正确反序列化您的 JSON 数据,您的 class 应该如下所示:

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; }
}

您可以使用 this 从 JSON 数据在 C# 中快速生成拟合模型。

商品 class 与您的 json 不匹配, 这是我对这种情况的建议:

    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; }
}

我创建了一个按钮来进行此转换

        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;

    }

添加了 gif:

您的 Item class 与 JSON 数据结构不匹配。您错过了 food 是 JSON 结构中的对象列表。您的项目 class 现在仅代表对象。它还错过了规则也是一个列表。

尝试:

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; }
}

您还需要将 Item 更改为 Root,如下所示:

Root item = JsonConvert.DeserializeObject<Root>(jsonString);

那么你应该像这样找到 fruit:

Console.WriteLine($"Fruit:" + item.food[0].fruit);