Deserialize Json data using Newtonsoft Json.NET library

As we learn to make more and more advanced apps, we need more tools in out kitty to make an amazing app. Local apps work great but they can only do so much. Exchanging data from a server or web service is very essential to make a dynamic and constantly updated app. Let’s see how to work with Json in Windows Phone 8 app using the Json.NET library.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

What is Json.NET library?

Json.NET is most popular, free and open source library to work with Json in Windows Phone or Windows apps. In this example, we will be learning how to parse Json data and store it in a variable which can be later used to bind that data to the UI elements such as a ListBox or LongListSelector
Let’s get started. I’ll be making a sample project with 1 style of Json and its parsing. But for the article I’ll be writing about one style, rest of the styles can be seen in the source code shared at the end of the article. Also, I won’t be covering DataBinding in this post, I shall cover that in a separate post. For the time being, the Json data is stored in a local text file stored in assets folder.

1. Adding Json.NET to your app

Go to the Nuget Package manager and search for Json.NET and add the Json.NET library to your project.

Nuget Package Manager
Adding Newtonsoft Json.NET

2. Add the following namespaces to your project

3. Convert the Json data into classes

To convert any Json data into it’s relevant classes, simple go to Json2Csharp and paste your data and this website will give you all the necessary classes. Or alternatively, yon can use the Visual Studio’s in built feature of Paste Json as Class feature from Edit -> Paste Special menu. This is my sample Json data used for this project:

Let’s understand what this data is, I’d suggest doing a search to understand the basic format of JSON data if you don’t already know. This is a object, mydata which is an array of objects. The objects in the array are all alike have 5 tags with different values in each object.

This is what the classes look like after converting the data into classes using Json2Csharp, don’t forget to paste these classes in you .cs file:

Now let’s take a moment to understand what these classes really mean. First class, MyData maps the object in the mydata array in our Json file. You can see the that this class has 5 variables with the same name as the our Json Objects in the mydata array. Second class, RootObject contains a list of class MyData, that means it acts like the array mydata as seen in our sample Json file. This RootObject is the container in which we will deserialize then Json data. It’ll then be a List of Json objects which we can use anyway we like. [DataBinding being a great use, which I will cover in another post.]

4. Read the Json data in a string

Since our file is locally hosted, we are simply reading the contents of the text file in a string using this function:
This function is called like this:

5. Deserialize

The final step.

Let’s see how and what really happened in the second statement(line 5). We created an object obj of class RootObject and then called DeserializeObject function for JsonConvert class and passed the variable containing our Json data as the parameter. That’s it and this data is now ready to be used in anyway you like. I’ll be making a tutorial on using this data with a DataBound LongListSelector soon.

Download source code from Github

Visit my website at chauhanvaibhav.net

Parsing and displaying simple XML feeds in Windows Phone 8 app

This post will explain how you could parse remotely located XML feeds and display content in Windows Phone 8 app. Here’s an sample XML file which we plan to fetch and display as a list in our app. If you are not familiar with XMLs then you could refer to some basic tutorials on w3schools.com. Here are few things worth remembering..

  • With XML, your data can be available to all kinds of reading machines
  • You can define any tag in XML, taking care of the fact that each tag opened should be closed
  • You can have any level of nesting of tags in XML
  • XML tags are case sensitive
  • In XML, all elements must be properly nested within each other
  • XML documents must contain one element that is the parent of all other elements.
  • In XML, the attribute values must always be quoted.

If you have a database on some server, you can easily create a web service for it and use the web service to get content for your app. This is useful when you already have things setup for your website and want to take it to mobile with native apps. Also if you have an app on one platform its easier to develop it for another using the same web services. It keeps your data synced and frees you from worrying about data inconsistency.

Here’s the PHP code which I used to generate the sample XML file. I fetch the rows from MySQL database and echo it within properly nested tags. You could pass GET/POST requests to filter the data which you want to return. For example, you may choose to display only authors with count greater than 20.

Now lets jump into building the app.

Step 1. Add a class Author to store the data for an author

In this tutorial we are fetching all the authors from a XML file. So we name our class Author which will store an author’s data.
Step 2. Add a list `authors` which will have items of type Author

Below the class Author add a list authors to store all the authors details



1

Step 3. Call a webclient on LayoutRoot_Loaded event to fetch the XML file

2

Add a loaded event handler for MainPage.xaml‘s LayoutRoot and add the code below to make a call to a WebClient and fetch the XML file.

  • We create a new instance of WebClient class
  • Invoke its OpenReadAsync function and specify the URL for your XML file
  • OpenReadCompleted calls client_OpenReadCompleted when the XML file at the specified URL has been downloaded
  • client_OpenReadCompleted has the code to parse the XML

 

 

Step 4. Parse the XML and store the data in the list `authors`

We earlier created a list `authors` to store the details of all the authors. We will use it now while parsing the XML.

  • The downloaded stream e.Result is stored in a Stream variable str
  • Next we create an instance of XDocument class and load the stream str in it and name it loadedData
  • We then iterate through all the descendants of the node author using a foreach loop
  • For each author we create a new instance of our class Author and add the values to it
  • We then add this Author object to our list `authors`
  • Finally we set the ItemSource of our ListBox to the list `authors`

authorlistbox.ItemsSource = authors;

Step 5. Create a Listbox to display all the authors using XAML

This ListBox will display the names of all the authors fetched from the XML file

  • We define the data template of the ListBox and a TextBlock to it
  • We bind the TextBlock with name. It is the same name which we used in our class Author
  • Give the ListBox some name, here we use authorlistbox

 

That’s all you need to do. Try deploying the app in the emulator and see how it works.

3

 

Suppose you have the XML stored locally in your app. Then you could use the following code to parse and display it.

Now that you have successfully displayed the content in a list box, lets try showing the count on ListBox_Selection_Changed. Most of the tutorials skipped this and I used to get struck here 😛
Get the full project source code here
Download full project source code XML-Parsing.zip

How to work with ListBox selected item in Windows phone application

In this post I am going to talk about different techniques of accessing a Listbox Selected item.

When we populate a Listbox with data items we have two options

1. First is that we can use Listbox items directly

2. Second we can make the use of databinding.

 

When we use option 1 the Selected item is usually the Listbox item so we can access it easily and perform the desired manipulations on it.

But when we make use of Second option which is the most widely used option the SelectedItem is the type of the business object (data class) which we use when performing data binding

There are different methods of accessing the ListBox Selected item which will be explained below with the help of an example.

 

In the following example I shall be creating a Listbox of student names along with a button which shall display their marks along with their name in a Texblock given below the List.

The different steps that need to be followed are

 

1. Create a new project Listboxselecteditem.

2. Then open the MainPage.xaml and remove the XAML code for the StackPannel named TitlePanel and replace it with the following code so as to change the page name and application name .

 


 

 

3. Now add the following Xaml code in the Grid named ContentPanel so as to create a list box in the page having the name mylistbox and bind the target Textblock nameblock  with data source name property. It also adds two Textblocks having the name Studentnameblock and marksblock to display the name and marks of selected student.

 



 

4. Now open the page MainPage.xaml.cs.

5. Create a public class called Resultclass having the properties name and marks in the page globally.


 

6. Then add the following code consisting of two global arrays for sample data to be used inside listbox named mylistbox

 

7. After that make a sample list from the data given above with the help of the following code given below.

 


 


 

8. Then call the function makeasamplelist in the constructor of the MainPage.xaml.cs.

 


 

If you face any problems while understanding the above code you can refer to the following blog post to understand the basics of data binding.

http://www.windowsapptutorials.com/windows-phone/data-binding-in-windows-phone-app-one-way-binding/

 

9. Now to add the following code for the Listbox SelectionChanged Event handler in the MainPage.xaml.cs.

This code will execute whenever you make a selection from the Listbox.

 


10. The code for the marks button Click EventHandler is as following. Whenever you click on the Marks button of a any Listbox item this code will execute.

 



.

11. Now run the application. You will see the following List created in your application.

 


 

12. Now Select any Listbox item. Suppose we select the second item that is Fred. When you will Select it the values of Textblocks Studentnameblock and marksblock will change respectively.

 


 

13. When you click on Marks button given in front of the student name the corresponding student name and marks will be shown in the Textblocks given below the Listbox.

When you Click on the Marks button given in front of James the following output will be shown.

 


 

14. If hope this post will be helpful to you. Download the full project zip file from the link given below.

 

Download full project file Listboxselecteditem.zip

 

How to bind ListBox to data in Windows phone application – Introduction

As an application developer, you can create ListBox controls without specifying the contents of each ListBoxItem separately. You can use data binding to bind data to the individual items.

In this post, I will explain with the help of an example how to create a ListBox that populates the ListBoxItem elements by data binding to a data source.

Suppose you want to display a list of students with their marks in a windows phone app. If we specify the contents of each item separately it would take a lot of time. So we make a use of data binding. The steps that need to be followed are

1. Create a new project ListboxBinding.

2. Then open the MainPage.xaml and remove the XAML code for the StackPannel named TitlePanel and replace it with the following code so as to change the page name and application name .

3. Now add the following Xaml code in the Grid named ContentPanel so as to create a list box in the page having the name mylistbox and bind the target Textblocks nameblock and marksblock with data source name and marks respectively.

 


 

4. Now open the page MainPage.xaml.cs.

5. Create a public class called Resultclass having the two properties name and marks.

6. Then add the following code consisting of two global arrays for sample data to be used inside listbox named mylistbox.

 

7. Then we can add the following data into the listbox in two ways.

First method:

First method is to create a Separate list for the Listbox and adding the items into that list. After that set the itemsource property of the Listbox to that of list created.

We can do this with the help of following code.

Second method: In second method instead of making a separate listbox we can directly add the items into the listbox. We can do this with the help of following code.
If you face any problems while understanding the above code you can refer to the following blog post to understand the basics of data binding.

http://www.windowsapptutorials.com/windows-phone/data-binding-in-windows-phone-app-one-way-binding/

8. Now call any one of the following method in the Constructor of the MainPage .Both will give the same list as the Output when you will run the application.

Suppose I call the firstmethod. Then the Constructor of the MainPage will look like


9. Now run the application on Emulator. You will see the following list created on the MainPage .


10. If you want to know more about the Listbox selected item you can refer to the following blog post

How to work with ListBox selected item in Windows phone application

11. I hope this post will be helpful to you. Download the project zip file from the link given below.

Download Full Project file ListboxBinding.zip

Checkout a related post on using ListView in android.

Using ListView in Android

Data binding in Windows Phone app – One way binding

Data binding provides a simple way for Windows Phone apps to display and interact with data. In simple terms it provides a link between the target and source. For example if we consider a Textblock and a data source whose object needs to update the value of text in Textblock we can use data binding.

 

We will now explain One way data binding in which bindings update the target with the source data when the binding is created.

Here source is a object of the class which needs to update the text property of Textblock (target).

 

The steps that need to be followed are

 

1. First of all create a blank project and name it Databinding .

 


 

2. Replace the Xaml code of the Stackpanel named Titlepanel with the following code given below.

 


 

Code:

<StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,17,0,28″>

<TextBlock Text=”Databinding” Style=”{StaticResource PhoneTextNormalStyle}” Margin=”12,0″/>

<TextBlock Text=”One way” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>

</StackPanel>

 

3. Add a Textblock named myblock to the given page . And bind the text property of the Textblock with mytext which is the property of the Sample class which will be explained further.

 



 

Add the code given below to the Grid named ContentPanel given on the page

Code:

<TextBlock x:Name=”myblock” HorizontalAlignment=”Left” Margin=”63,80,0,0″ TextWrapping=”Wrap” Text=”{Binding mytext}” VerticalAlignment=”Top” Height=”57″ Width=”330″ FontSize=”28″/>

 

4. Open the Page MainPage.xaml.cs and Create a Public class having the name Sampleclass with a single property mytext.

 


 

Code:

public class Sampleclass

{

public string mytext { get; set; }

}

 

5. Add the function given below to the MainPage.xaml.cs .

 

Code:

public void initialize()

{

Sampleclass obj = new
Sampleclass();

obj.mytext = “One way data binding”;

myblock.DataContext = obj;

}

 

In the first line of the function we are creating a object of Sampleclass called obj. In the second line we are setting the mytext property of the object to “One way data binding”.

In the third line we set the source of the myblock by setting up its Datacontext property to obj.

 

6. We then call this function in the constructor of the MainPage.

 


 

7. Now when we run the application we will see that the Content of myblock will be “One way data binding” as shown below.

 


 

8. I hope this post will be helpful to you.Download the project zip file from the link given below.

 

Download full project