We need to read and display the data from local JSON file sometimes in our apps. Here I will explain how to read local JSON files in Windows 10 app.
I am going to use Newtonsoft.Json library to parse the JSON string.
Let’s see the steps.
Create new Windows 10 app and add the JSON file that you want to read, here I add the following JSON file to load the country’s details.
Next, create a data class used to parse the JSON values it looks like the following code.
- [DataContract]
- public class Country
- {
- private string _code = string.Empty;
- [DataMember]
- public string name
- {
- get;
- set;
- }
- [DataMember]
- public string iso_code
- {
- get;
- set;
- }
- [DataMember]
- public string code
- {
- get
- {
- return _code.Trim();
- }
- set
- {
- _code = value;
- }
- }
- }
Add ListBox control to list the country details from JSON file.
- <ListView x:Name="countryList">
- <ListView.ItemTemplate>
- <DataTemplate>
- <StackPanel Orientation="Horizontal">
- <TextBlock Height="50" Width="50" Text="{Binding name}"></TextBlock>
- </StackPanel>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
Here, I am binding the country name in the listbox.
Before that we need to add the Newtonsoft.Json NuGet package like the following screen.
Now read the JSON file and assign the data to listbox using the following code.
Get the file path and read the file using StreamReader then deserialize the json string using NewtonSoft JSON.
- string FilePath = Path.Combine(Package.Current.InstalledLocation.Path, "country_list.json");
- using(StreamReader file = File.OpenText(FilePath))
- {
- var json = file.ReadToEnd();
- Dictionary < string, object > result = Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, object >> (json);
- string contacts = result["country_list"].ToString();
- List < Country > objResponse = Newtonsoft.Json.JsonConvert.DeserializeObject < List < Country >> (contacts);
- countryList.ItemsSource = objResponse;
- }
Now run the app and see the excepted output looks like the following screen.