C# 反序列化要添加到ints c列表中的Json文件
我能够使用JSON序列化程序将对象列表写入文本文件,但我的目标是根据需要从JSON文本文件填充列表。我有点不明白该怎么做。我对JSON一点经验都没有,今天只是第一次使用它 下面是我用来将int列表写入JSON的代码C# 反序列化要添加到ints c列表中的Json文件,c#,json,listview,serialization,C#,Json,Listview,Serialization,我能够使用JSON序列化程序将对象列表写入文本文件,但我的目标是根据需要从JSON文本文件填充列表。我有点不明白该怎么做。我对JSON一点经验都没有,今天只是第一次使用它 下面是我用来将int列表写入JSON的代码 class LockTime { public int Start { get; set; } public int End {get; set; } public LockTime (int start, int end) {
class LockTime
{
public int Start { get; set; }
public int End {get; set; }
public LockTime (int start, int end)
{
Start = start;
End = end;
}
}
这是我正在编写JSON文件的类,或者是我正在编写JSON文件的部分
private List<LockTime> times;
int timeStart = pickerTimeStart.Value.Hour + pickerTimeStart.Value.Minute;
int timeEnd = pickerTimeEnd.Value.Hour + pickerTimeEnd.Value.Minute;
LockTime bla = new LockTime(timeStart, timeEnd);
times.Add(theTime);
string meh = JsonConvert.SerializeObject(times, Formatting.Indented);
File.WriteAllText(@filePath, meh);
我想做两件事。第一个是从json文件填充listview。伪码
使用以下内容反序列化文件
times=JsonConvert.DeserializeObject>json
但是我不知道如何从文本文件直接转到数组,然后如何在listview中显示它。在使用JSON之前,我使用的是一个简单的文本文件,其中我首先一行一行地绘制一组int,然后通过lstTime.Items.AddRangeGetTimes.Selectt=>new ListViewItemt.ToArray在listview中显示它们
知道怎么做吗?除非我弄错了,这里的问题涉及使用JSON.NET序列化和反序列化。以下是一些很好的SO资源: 以下内容将序列化并反序列化您拥有的列表,然后从这些对象中检索整数列表:
// Assume there is some list of LockTime objects.
List<LockTime> listOfTimes = new List<LockTime>
{
new LockTime(1, 5),
new LockTime(10, 15)
};
// Serialize this list into a JSON string.
string serializedList = JsonConvert.SerializeObject(listOfTimes, Formatting.Indented);
// You can write this out to a file like this:
//File.WriteAllText("path/to/json/file", serializedList);
// You can then read it back in, like this:
//var serializedList = File.ReadAllText("path/to/json/file")
// To get a list of integers, you can do:
List<LockTime> deserializedList = (List<LockTime>)JsonConvert.DeserializeObject(serializedList, typeof(List<LockTime>));
// Grab whatever data you want from this list to store somewhere, such as a list of all Start integers.
List<int> intList = deserializedList.Select(entry => entry.Start).ToList();
你想要完成的事情会更清楚,有更多的背景。我建议将更多的代码发布到,从社区获得一些有用的反馈和提示。哇,太快了,谢谢你的帮助。我将尝试实现这一点。我的整数基本上是次,所以我第一次传递给Json文件的整数的格式是start 2000 end 2010等。所以在listview中,我需要它们显示出来,它显示start和end等
lstTime.Items.AddRange(intList.Select(t => new ListViewItem(t.ToString(CultureInfo.InvariantCulture))));