Read JSON File In Windows 10 Universal App

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.

code

Next, create a data class used to parse the JSON values it looks like the following code.

  1. [DataContract]  
  2. public class Country   
  3. {  
  4.     private string _code = string.Empty;  
  5.     [DataMember]  
  6.     public string name  
  7.     {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     [DataMember]  
  12.     public string iso_code   
  13.     {  
  14.         get;  
  15.         set;  
  16.     }  
  17.     [DataMember]  
  18.     public string code   
  19.     {  
  20.         get  
  21.         {  
  22.             return _code.Trim();  
  23.         }  
  24.         set  
  25.         {  
  26.             _code = value;  
  27.         }  
  28.     }  
  29. }  
Add ListBox control to list the country details from JSON file.
  1. <ListView x:Name="countryList">  
  2.     <ListView.ItemTemplate>  
  3.         <DataTemplate>  
  4.             <StackPanel Orientation="Horizontal">  
  5.                 <TextBlock Height="50" Width="50" Text="{Binding name}"></TextBlock>  
  6.             </StackPanel>  
  7.         </DataTemplate>  
  8.     </ListView.ItemTemplate>  
  9. </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.

add

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.
  1. string FilePath = Path.Combine(Package.Current.InstalledLocation.Path, "country_list.json");  
  2. using(StreamReader file = File.OpenText(FilePath))   
  3. {  
  4.     var json = file.ReadToEnd();  
  5.     Dictionary < stringobject > result = Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < stringobject >> (json);  
  6.     string contacts = result["country_list"].ToString();  
  7.     List < Country > objResponse = Newtonsoft.Json.JsonConvert.DeserializeObject < List < Country >> (contacts);  
  8.     countryList.ItemsSource = objResponse;  
  9. }  
Now run the app and see the excepted output looks like the following screen.

output

 

Up Next
    Ebook Download
    View all
    Learn
    View all