Parsing JSON data from Windows 8

 

Parsing JSON data from Windows 8

Rate This
  • Comments 2
This post is about parsing JSON data from Windows 8 clients, or from applications that support version 4.5 of the .Net framework.

Let’s begin with some imaginary JSON data.
JSON Data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
[ { "backgroundImage" : "images/Chinese/Chinese_1_600_C.jpg",
    "directions" : "Mix the ground pork with the salt, sugar, pepper, cornstarch and sesame oil. Add the dried mushrooms and Chinese sausage.Divide into 18 approximately equal portions. Take one portion of the meat and slightly flatten in your hand. Place a cooked quail egg on top of the meat and cover the meat around the egg to make a small round ball. Set aside. Dough:Mix the flour and sugar in a big bowl. Pour the milk in and mix until it becomes a dough Let it sit for 5 minutes. Divide into about 18 equal portions. If you feel any lumps, work through the dough with your hands to remove them. Forming and Cooking the Buns: flour, 18 pieces of dough, 18 balls of meat filling,  parchment paper, cut into 18 square. On a floured surface, roll out a piece of dough into a circle, ideally tapered at the edges Dip one of the prepared meat fillings in flour, With the piece of dough in one hand, place the meat filling on top. ",

    "extraImages" : [ { "image" : "images/Chinese/Chinese_1_600_C.jpg" },

        { "image" : "images/Chinese/Chinese_2_600_C.jpg" },

        { "image" : "images/Chinese/Chinese_3_600_C.jpg" }

      ],

    "favorite" : false,

    "group" : { "backgroundImage" : "images/Chinese/chinese_group_detail.png",

        "description" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis laoreet tempus libero vitae feugiat. Proin justo velit, luctus ornare posuere eget, pulvinar ac nibh. Integer dapibus leo in metus volutpat blandit. Morbi facilisis laoreet magna iaculis porta. Donec quis ipsum et justo faucibus lacinia. Vivamus id sapien nec dolor venenatis hendrerit. Aenean sit amet pretium quam. ",

        "groupImage" : "images/Chinese/chinese_group.png",

        "key" : "Chinese",

        "rank" : "",

        "recipesCount" : 6,

        "shortTitle" : "Chinese",

        "title" : "Chinese"

      },

    "ingredients" : [ "600 g Ground pork",

        "1 tsp Salt",

        "1 tsp sugar",

        "1/2 tsp Ground black pepper",

        "2 tsp Cornstarch",

        "1 tbsp Sesame oil",

        "1 handful Sliced dried mushrooms ",

        "soaked and well drained",

        "18 Quail eggs",

        "cooked and peeled - alternately use 5 chicken eggs and cut them into quarters ",

        "3/4 cup Sugar",

        "4 1/2 cups Self-raising flour",

        "1 1/2 cups Milk"

      ],

    "key" : 1000,

    "preptime" : 60,

    "rating" : 4,

    "shortTitle" : "Steam bun baos",

    "tileImage" : "images/Chinese/Chinese_1_150_C.jpg",

    "title" : "Steam bun baos"

  }

]



I’m storing this as a resource that I’ve added to my Visual Studio project. The name of the resource file is Resources.resw.

You can easily add resource files to your Visual Studio project. Simply go to the Project menu and select add new item. From there navigate down and choose resources file.

magbvvo0
If I open up the resource editor, it looks like this:
ggwrtanr


The Code behind Now that I’ve explained the data that we wish to parse, let’s look at some C sharp code to actually do the parsing. In the code below you can see that I’ve arbitrarily chosen two items inside the JSON data. I have chosen backgroundImage and extraImages. The code is fairly self-explanatory as seen below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using Windows.ApplicationModel.Resources;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace ReadJson
{
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            GetData();
        }

        ///
        /// Invoked when this page is about to be displayed in a Frame.
        ///

        /// "e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        public void GetData()
        {
            //
            // Read the data as a big string
            //
            var resourceLoader = new ResourceLoader();
            var result = resourceLoader.GetString("JSONDATA"); // see string above
                                                                // I stored the string in a resource file

            //
            // Parse the JSON data
            //
            try
            {
                var parsedResponse = JsonArray.Parse(result);
                //
                // Convert to a JSON array
                //
                JsonArray array = parsedResponse;

                IJsonValue outValue;
                foreach (var item in array)
                {
                    JsonObject obj = item.GetObject();
                    // Assume there is a “backgroundImage” column coming back
                    if (obj.TryGetValue("backgroundImage", out outValue))
                    {
                        string backgroundImage = outValue.GetString();
                        // backgroundImage = images/Chinese/Chinese_1_600_C.jpg
                    }
                    // Assume there is a “backgroundImage” column coming back
                    if (obj.TryGetValue("extraImages", out outValue))
                    {
                        JsonArray arrayObj = outValue.GetArray();

                        foreach (var itemImage in arrayObj)
                        {
                            JsonObject imageObj = itemImage.GetObject();
                            string image1 = imageObj.GetNamedValue("image").GetString();
                            // image1 = images/Chinese/Chinese_1_600_C.jpg,
                            // then   = images/Chinese/Chinese_2_600_C.jpg
                            // then   = images/Chinese/Chinese_3_600_C.jpg
                        }


                       
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
                throw;
            }

        }

    }
}


The .NET framework provides excellent support for parsing JSON data. Notice the method calls of TryGetValue(), which essentially lets you “probe” to see if a particular data item exists.  I hope this eliminates some of the challenges of parsing JSON data for developers.
  • theres a simpler way

    just use json2csharp.com to get your Object..

    Then just JsonConvert.DeserializeObject<RootObject>(resourceLoader.GetString("JSONDATA"))

    Now just use this with you MVVM Models ....

  • Hi dude, sorry for not hearing in for quite some time, but I've been "busy" as you can see ... ;)

    Anyway, I've got this Mono/.Net initiative going with the Active Event system, which I think you would want to take a look at ...

    magixilluminate.wordpress.com

    In fact, send a link to Scott Guthrie if you wish, it's pretty amazing what these little guys seems to be able to do. Among other things I can turn an entire network into a JSON connected mesh of applications, interconnected and passing any amounts of integrations back and forth, invoking remote functions, polymorphistically, on a need basis, for instance ...

    Unfortunately, currently there's only a source release, and it only works with Mono Develop, I think ...?

    My new email is MareMara13@gmail.com

Page 1 of 1 (2 items)
Leave a Comment
  • Please add 7 and 1 and type the answer here:
  • Post