I just had need of reading a small JSON file into a Windows 8 application using the Windows Runtime.
Uri uri = new Uri("ms-appx:///assets/data.json");
var storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
using (var storageStream = await storageFile.OpenReadAsync())
using (Stream stream = storageStream.AsStreamForRead())
using (StreamReader reader = new StreamReader(stream))
var jsonText = reader.ReadToEnd();
var results = JsonConvert.DeserializeObject<DemoData>(jsonText);
this.DataContext = results;
What seemed like it should have been a common example on MSDN was not …, and after a bit of searching and reading, I believe the above code represents at least a common and safe way of loading data.
I’ve got a file called data.json stored in an Assets folder:
And the file’s Build Action is set to Content:
Change the value passed to the Uri constructor and … the file will be loaded successfully. Once loaded, I used the strongly typed generic DeserializeObject method to convert the Json data to a class called DemoData.