酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Windowsストアアプリでネット上にあるJSONファイルをダウンロードしてパースする

最近はウェブサービスから情報を取得する際にXMLよりもJSONで返すサービスが増えてきました。

Windowsストアアプリで、ネット上にあるJSONファイルをダウンロードしてパースしてみましょう。

JSONファイルをダウンロードしてパースする

ダウンロードするJSON

ダウンロードしてきてパースする対象となるJSONファイルは以下のようなものです。idtitleが含まれるオブジェクトが複数個含まれている配列を想定しています。

[
    {
        "id": 2,
        "title": "コンテンツアップデート"
    },
    {
        "id": 1,
        "title": "バージョン1.2リリース"
    }
]

取得したJSONを表示するXAML

ボタンをクリックするとButton_Clickを実行して、TextBlockにパースした結果を表示するようにします。

<Page
    x:Class="LoadJsonSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LoadJsonSample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="Result" HorizontalAlignment="Left" Margin="61,151,0,0" 
                   TextWrapping="Wrap" VerticalAlignment="Top" Height="561" Width="306"/>
        <Button Content="JSONを取得する" HorizontalAlignment="Left" Margin="58,61,0,0" 
                VerticalAlignment="Top" Width="221" Height="49" Click="Button_Click"/>
    </Grid>
</Page>

XAMLデザイナーでButtonとTextBlockを下図のように配置しました。

f:id:ch3cooh393:20140922134109p:plain

JSONファイルをパースする

Button_Click の挙動を紹介します。

using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;

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

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var url = new Uri("http://example.com/infomation.json");

            // (1) ウェブ上のJSONファイルを取得する
            var client = new HttpClient();
            var jsonText = await client.GetStringAsync(url);

            // JSONをパースした結果を格納するリスト
            var list = new List<string>();

            // (2) テキストを配列のJSONとしてパースする
            var array = Windows.Data.Json.JsonArray.Parse(jsonText);
            foreach (var item in array)
            {
                if (item.ValueType != Windows.Data.Json.JsonValueType.Object)
                {
                    continue;
                }

                var obj = item.GetObject();

                var id = obj.GetNamedNumber("id");
                var title = obj.GetNamedString("title");

                list.Add(string.Format("{0}: {1}", id, title));
            }

            // (3) TextBlockに表示する
            Result.Text = string.Join("\n", list);
        }
    }
}

ボタンをクリックすると、下図のようにJSONファイルの中身が表示されます。

f:id:ch3cooh393:20140922134139p:plain

サンプルプロジェクト