我有一个文件 Add.xaml在里面,我有我的食谱类,它将我的食谱对象存储在名为 breakfastRecipe 的列表中
然后,我将列表beakfastRecipe存储在breakfast.json文件中。(使用我从另一个成员那里找到的反序列化/序列化方法)
我有几个文本框,我在其中写下名称+成分,然后我使用一个保存按钮来激活json序列化程序。我使用测试方法来测试反序列化程序是否一切正常并且确实如此。在 add.xaml 页面上,对象列表的保存和加载工作正常
我有另一个页面breakfastList.xaml,我想使用longlistselector用我所有的食谱填充我的页面。问题是我不知道如何访问在另一个页面上创建的 breakfast.json 文件。
我使用相同的获取/反序列化程序来加载我的数据
public async void btnGet_Tap()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
try
{
// Getting JSON from file if it exists, or file not found exception if it does not
StorageFile textFile = await localFolder.GetFileAsync("breakfastList.json");
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
// Read text stream
using (DataReader textReader = new DataReader(textStream))
{
//get size
uint textLength = (uint)textStream.Size;
await textReader.LoadAsync(textLength);
// read it
string jsonContents = textReader.ReadString(textLength);
// deserialize back to our products!
//I only had to change this following line in this function
breakfastRecipe = JsonConvert.DeserializeObject<IList<Recipe>>(jsonContents) as List<Recipe>;
// and show it
//displayProduct();
}
}
}
catch (Exception ex)
{
tester.Text = "error";
}
}
当我在构造函数中编写时
早餐食谱 = 新列表();btnGet_Tap();
在我看来,我正在创建一个新列表,然后 btnGet 从我的 add.xaml 创建的那个 .json 文件中加载数据,但它不起作用......
然后我的问题是如何访问我的"第二页"上的数据,该"第二页"存储在由我的第一页创建的.json文件中
尝试将btnGet_Tap代码移动到一个异步函数中,该函数返回一个任务,然后在 btnGet_Tap() 方法中等待。然后,您可以致电
Foo().Wait();
如果您希望在调用构造函数时等待。
public async void btnGet_Tap()
{
await Foo();
}
public async Task Foo()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
try
{
// Getting JSON from file if it exists, or file not found exception if it does not
StorageFile textFile = await localFolder.GetFileAsync("breakfastList.json");
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
// Read text stream
using (DataReader textReader = new DataReader(textStream))
{
//get size
uint textLength = (uint)textStream.Size;
await textReader.LoadAsync(textLength);
// read it
string jsonContents = textReader.ReadString(textLength);
// deserialize back to our products!
//I only had to change this following line in this function
breakfastRecipe = JsonConvert.DeserializeObject<IList<Recipe>>(jsonContents) as List<Recipe>;
// and show it
//displayProduct();
}
}
}
catch (Exception ex)
{
tester.Text = "error";
}
}