我必須讀取本地存盤在我的機器中的 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);
物品類別:
public class Item
{
public string fruit;
public string size;
public string color;
public string id;
public string rules;
}
PS:如果我注意到這段代碼只有在我的資料結構沒有“食物”塊的情況下才能作業,它認為這就是問題所在。關于如何解決這個問題的任何想法?
uj5u.com熱心網友回復:
專案類不代表JSON 資料的正確結構。您有一個根物件,其中包含一個屬性,該屬性是另一個物件的串列。
要正確反序列化您的 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 Root
{
public List<Food> food { get; set; }
}
您可以使用
uj5u.com熱心網友回復:
您的Item類與 JSON 資料結構不匹配。您錯過了food是 JSON 結構中的物件串列。您的 Item 類現在僅代表 Object。它也錯過了規則也是一個串列。
嘗試:
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);
然后你應該找到這樣的水果:
Console.WriteLine($"Fruit:" item.food[0].fruit);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/416887.html
標籤:
上一篇:Java中的BufferedReader正在跳過檔案中的最后一個空行
下一篇:SVG中的“深度”影片
