我有这个对象,我想再添加一天。
[{
"stone":"5kg",
"years":
[{
"year":"2017",
"stone":"5kg",
"months":
[{
"month":"august",
"stone":"0.5kg",
"days":
[{
"day":"14",
"stone":"0.1kg"
}]
}],
"weeks":
[{
"week":"01",
"stone":"0.5kg"
}]
}]
}]
我将它存储在一个文件中,然后像这样反序列化它:
string file = System.IO.File.ReadAllText(@"C:\Users\luuk\desktop\test1.json");
var _data = JsonConvert.DeserializeObject<List<Data>>(file);
现在我想给它添加一天,但我就是想不通。我试过这样的事情:
_data.Add(new Data()
{
});
string json = JsonConvert.SerializeObject(_data);
System.IO.File.WriteAllText(@"C:\Users\luuk\desktop\test1.json", json);
但我只能在那里访问 years[] 和石头。
这些是我的课程:
public class Data
{
public string stone { get; set; }
public List<Years> years { get; set; }
}
public class Years
{
public string year { get; set; }
public string stone { get; set; }
public List<Months> months { get; set; }
public List<Weeks> weeks { get; set; }
}
public class Months
{
public string month { get; set; }
public string stone { get; set; }
public List<Days> days { get; set; }
}
public class Days
{
public string day { get; set; }
public string stone { get; set; }
}
public class Weeks
{
public string week { get; set; }
public string stone { get; set; }
}
那么如何为对象添加另一天呢?
(我已将代码中的所有变量从荷兰语翻译成英语,所以有些我忘记了或有一些错字)
您需要首先获取要添加另一天的年份和月份。您可以这样做:
// Update the data in one line
_data[0].years.First(x=> x.year == "2017") // Get the year "2017"
.months.First(x=> x.month == "august") // Get the month "august"
.days.Add(new Days { day = "15", stone = "0.5kg" }); // Add a new day
或者
// Get the year
Years year = _data.years.First(x=> x.year == "2017");
// Get the month
Months month = year.months.First(x=> x.month == "august");
// Add the day in the month
month.days.Add(new Days { day = "15", stone = "0.5kg" });
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句