Wednesday, December 26, 2012

Windows Phone JSON Parsing Example Part-1

we can parse a json document in windows  phone applications easily and it is easy to implement and understand.

1) please make a new project with the name JSONParsingExample and copy following xaml layout to MainPage.xaml


<phone:PhoneApplicationPage
    x:Class="JSONParsingExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

 

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Button x:Name="myButton" Grid.Row="0" Height="75" Content="Click to Call JSON service " VerticalAlignment="Top" />
            <ListBox Name="lstEmployee"  Height="150" Grid.Row="2" FontSize="24" VerticalAlignment="Top"></ListBox>
        </Grid>
    </Grid>

    <!--Sample code showing usage of ApplicationBar-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
                <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>

2) now please copy the following code to yours MainPage.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.IO;
using System.Text;

namespace JSONParsingExample
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            myButton.Click += new RoutedEventHandler(myButton_Click);
        }
        void myButton_Click(object sender, RoutedEventArgs e)
        {

         
            try
            {
                WebClient webClient = new WebClient();
                Uri uri = new Uri("http://docs.blackberry.com/sampledata.json");
                webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                webClient.OpenReadAsync(uri);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "error came here 1");
            }
        }
        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {


            DataContractJsonSerializer ser = null;
            try
            {
                ser = new DataContractJsonSerializer(typeof(ObservableCollection<RootObject>));
                ObservableCollection<RootObject> employees = ser.ReadObject(e.Result) as ObservableCollection<RootObject>;
                foreach (RootObject em in employees)
                {
                    string id = em.vehicleColor + "|" + em.vehicleType + "|" + em.fuel + "|" + em.treadType+"|";
                    //string nm = em.GetRoot.Customer.CustomerID;
                    lstEmployee.Items.Add("<="+id + "=>" );
                    foreach (var error in em.approvedOperators)
                    {
                        lstEmployee.Items.Add("**" + error.experiencePoints+"|"+error.name);
                    }
                }



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "error came here 2" + ex.StackTrace);
            }


        }
        public class ApprovedOperator
        {
            public string name { get; set; }
            public int experiencePoints { get; set; }
        }

        public class RootObject
        {
            public string vehicleType { get; set; }
            public string vehicleColor { get; set; }
            public string fuel { get; set; }
            public List<ApprovedOperator> approvedOperators { get; set; }
            public string treadType { get; set; }
        }
    }
}

3) you need to take care of the references. i used Newtonsoft.Json.dll in my example so you need to add it to yours reference.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.IO;
using System.Text;  

these above are the used references in this demo example code!!

4) run code successfully on emulator and you can see the out put after clicking the  "Click to Call JSON service" button



You need to get some getters and setters which you can get with the help of

http://json2csharp.com/


put the url there and you will get the supporting classes

i used the link http://docs.blackberry.com/sampledata.json for the demo example
:)


for Newtonsoft.json.dll you can use the link http://www.4shared.com/file/qXtiES9U/NewtonsoftJson.html or you can search with the other links as well through google!!


16 comments:

  1. Hi Warren sorry that it is not useful to you. but i am taking it positively and please let me know that how can i help you, i gave the the code which i worked, if you really need a help on the sliver-light code please ask and i will try to help you. hope the post will be useful for you later.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. hi please debug the code again please, it was working fine for me, if you need further help please send the code or write a note regarding yours need i will try to write the code on same.

    ReplyDelete
  4. hi how do i make this work with a php rest json response instead of a json file?

    ReplyDelete
    Replies
    1. Hi As you wants to use the php rest json, so make an http rest client and work with that , get the response and parse it in the same way. if you have any problem to do that, i will try to help You.

      Delete
  5. hello ,I am learning windows phone app development.In my demo app ,login page like other website.i want to perform authentication from user input.checks that user is registered or not .i try your code but it cant work .i am using vs2012 ultimate,WP sdk 8.0 and database in MySQL .how can i do it .can you show me it with example.My email
    address is akakadiya91@gmail.com

    ReplyDelete
    Replies
    1. hi please debugthe code and please inform what errors you are getting!!

      Delete
    2. your code help me for solving issues.thank you.

      Delete
  6. suppose one more class is output of json2C# .and not any change in root object class.than i am want to display that one class data in my phone then how it would be possible .thank you

    ReplyDelete
    Replies
    1. Please parse the parts what you need and choose only those class object values which you needed.

      Delete
  7. Hey jitesh i try this example for json parsing but when i wanted to add newtonsoft reference to my project i get this error:
    A reference of a higher version or incompatible assemly cannot be added to the project.

    ReplyDelete
    Replies
    1. Allow visual studio to reference those dll by unblocking that dll.

      Right-click on each of the dll file that you want to reference
      select Properties and then click on the Unblock button.

      Your project is compiled to be 7.0 i think and the silverlight was for 7.1 sdk. Just set the project to 7.1.....

      Delete
    2. I have the same problem,

      How should I change it to 7.1?

      I don't see any unblock button when i select Properties.

      Delete
    3. hi please go through the properties and change them :) hope it will help you and will solve yours problem.

      Delete
  8. I didnt get the proper classes for the below json. I used the below class for Parsing, but it gave me a null.(From the below code, feed object has NULL).

    I used http://json2csharp.com/.

    I always get a null on deserialisation of response. Whats the mistake here or anyother good way to this??

    Thanks.

    My code:

    var feed = Newtonsoft.Json.JsonConvert.DeserializeObject(data);

    json response:
    {"application-name":["hello-world",{"form-name":["Untitled_Form",{"Fields":[{"Tooltip":"","MaxChar":255,"Unique":false,"FieldName":"Single_Line","Type":1,"Initial":"","DisplayName":"Single Line","Reqd":false},{"Tooltip":"","MaxChar":255,"Unique":false,"FieldName":"Email","Type":4,"Initial":"","DisplayName":"Email","Reqd":false}],"DisplayName":"Untitled Form"}]}]}

    C# Classes:
    public class RootObject
    {
    public ListOfObject __invalid_name__application-name { get; set; }
    }

    ReplyDelete
  9. Concerning Parse analytics itself, the organization is developing at a 40 percent month-over-month rate and has around 16,000 applications on the stage. It’s a freemium administration,

    ReplyDelete