[英]Populate List with Json file
我有一個物品清單。 Item是具有多個構造函數的對象,因此可以多種形式創建一個Item。
具有兩個構造函數的Item類的示例。
public class Item
{
public string name = "";
public int age= 0;
public int anotherNumber = 0;
public Item(string iName, int iAge)
{
name = iName;
age= iAge;
}
public Item(string iName, int iAge, int iAnotherNumber)
{
name = iName;
age= iAge;
}
}
然后,我有一個Json文件,格式為:-
[{"name":"Joseph","age":25},{"name":"Peter","age":50}]
我正在使用以下方法使用Newtonsoft.Json API讀取文件並填充列表。
public List<Item> ReadJsonString()
{
List<Item> data = new List<Item>();
string json = File.ReadAllText("\\path");
data = JsonConvert.DeserializeObject<List<Item>>(json);
return data;
}
如果Item類中只有一個構造函數(例如,帶有2個參數的構造函數),則此方法可以正常工作,並且我可以填充列表。 但是,當我在Items類中添加第二個構造函數時(因為我希望也能夠讀取具有第三個屬性的Json文件。
例:-
[{"name":"Joseph","age":25, "anotherNumber": 12},{"name":"Peter","age":50, "anotherNumber": 12}]
ReadJsonObj方法失敗,錯誤為“無法找到用於類型Item的構造函數”。 我可以通過創建多個類Item(例如ItemA,ItemB)來解決此問題,一個類接受三個變量,另一個接受兩個變量。 但是,我只想擁有一個Item類。
我不知道為什么會這樣以及如何解決這個問題。
您可以使用properties
代替常規字段和構造函數初始化。
public class Item
{
public string name {get;set;}
public int age {get;set;}
public int anotherNumber {get;set;}
}
因此,您將介紹兩種反序列化情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.