新時尚Windows8開發(32):Json資料處理(A)

來源:互聯網
上載者:User

JSON是啥?大家不陌生了吧,估計有人比我還懂,這玩意兒其實我只懂點皮毛,對,就是皮毛,皮和毛,皮包著毛,你看看JSON對象是不是這樣?

外面套著一對大括弧({})是皮,裡面有很多毛毛,其實一個JSON對象就好像一個字典集合,有key,也有value,當然,也可以沒有key。你看,一個標準的JSON對象大概是這樣的。

{

      '鍵名' : 索引值,

      '鍵名' :  索引值,

      '鍵名' : 索引值

}

 

如果是集合,如數組之類的,就多個對象放在 [ ...] 中,用逗號隔開,記得是英文的逗號。

 

 

案例1:從JSON字串產生JSON對象

這個例子,我們來“調研”一下,如何從一個JSON結構的字串產生一個JSON對象。

1、建立一個空白頁面的“板磚”風格應用。

2、首頁的布局就直接Ctrl + V XAML代碼了,不然又有人說:“這和Win8有毛關係啊,這不是WPF中的XAML嗎?”

<Page    x:Class="App3.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:local="using:App3"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d">        <Page.Resources>        <Style x:Key="tbstyle" TargetType="TextBlock">            <Setter Property="FontSize" Value="25"/>        </Style>    </Page.Resources>    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">        <StackPanel Margin="20">            <Button Content="從JSON字串產生對象" Click="onClick"/>            <Grid Margin="5,19,6,0">                <Grid.RowDefinitions>                    <RowDefinition Height="auto"/>                    <RowDefinition Height="auto"/>                    <RowDefinition Height="auto"/>                    <RowDefinition Height="auto"/>                </Grid.RowDefinitions>                <Grid.ColumnDefinitions>                    <ColumnDefinition Width="auto"/>                    <ColumnDefinition Width="auto"/>                </Grid.ColumnDefinitions>                <TextBlock Grid.Row="0" Grid.Column="0" Text="編號:" Style="{StaticResource tbstyle}"/>                <TextBlock x:Name="tbNO" Grid.Column="1" Grid.Row="0" Style="{StaticResource tbstyle}"/>                <TextBlock Grid.Column="0" Grid.Row="1" Text="姓名:" Style="{StaticResource tbstyle}"/>                <TextBlock x:Name="tbName" Grid.Row="1" Grid.Column="1" Style="{StaticResource tbstyle}"/>                <TextBlock Grid.Column="0" Grid.Row="2" Text="城市:" Style="{StaticResource tbstyle}"/>                <TextBlock x:Name="tbCity" Grid.Row="2" Grid.Column="1" Style="{StaticResource tbstyle}"/>                <TextBlock Grid.Row="3" Grid.Column="0" Text="年齡:" Style="{StaticResource tbstyle}"/>                <TextBlock x:Name="tbAge" Grid.Row="3" Grid.Column="1" Style="{StaticResource tbstyle}"/>            </Grid>        </StackPanel>    </Grid></Page>

 

3、背景代碼,主要是處理按鈕的Click事件,我貼個完整的。

using System;using System.Collections.Generic;using System.IO;using System.Linq;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;using Windows.Data.Json;namespace App3{    /// <summary>    /// 可用於自身或導航至 Frame 內部的空白頁。    /// </summary>    public sealed partial class MainPage : Page    {        public MainPage()        {            this.InitializeComponent();        }        private void onClick(object sender, RoutedEventArgs e)        {            // JSON字串            string jsonString = "{" +                                    "\"No\":\"000-2145\"," +                                    "\"Name\":\"小王\"," +                                    "\"City\":\"天津\"," +                                    "\"Age\":185" +                                "}";            // 產生JSON對象            JsonObject obj = JsonObject.Parse(jsonString);            // 從JSON對象中取出資料            this.tbNO.Text = obj.GetNamedString("No");            this.tbName.Text = obj.GetNamedString("Name");            this.tbCity.Text = obj.GetNamedString("City");            this.tbAge.Text = obj.GetNamedNumber("Age").ToString();        }    }}

從代碼中,你會看到,要處理與JSON有關的資料,先引入Windows.Data.Json命名空間。

因為我們的JSON對象是帶命名鍵的,所以,在產生JsonObject後,可以通過調用以下方法來取得對應欄位的值:

【對JSON來說,無非就是字串,布爾類型,數值,數組或者綜合物件】

GetNamedArray —— 如果對應欄位是一個JSON對象數組,就可以考虎調用該方法。

GetNamedBoolean,GetNamedNumber,GetNamedString,GetNamedObject —— 這些方法就簡單了,都是取出單個指定類型的值。

現在運行一下,點擊頁面最上方的按鈕,就會看到結果了。

 

 

案例2:將JSON對象轉換為字串

本個例子貌似和上面的例子相反,是將JSON對象變成字串表示形式。

1、建立應用程式項目。

2、MainPage.xaml的UI如下:

<Page    x:Class="App1.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:local="using:App1"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d">    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">        <StackPanel Margin="20">            <Button Content="產生JSON字串" Click="onClick"/>            <TextBox x:Name="txtJson" Margin="8,17,8,0" Height="400" TextWrapping="Wrap" FontSize="20"/>        </StackPanel>    </Grid></Page>

單擊按鈕後,產生JSON對象,並在下面的TextBox中顯示轉換的字串。

 

3、處理按鈕的Click事件。記得引入Windows.Data.Json命名空間。

        private void onClick(object sender, RoutedEventArgs e)        {            // 建立第一團隊的成員對象            JsonObject menb1 = new JsonObject();            menb1.SetNamedValue("姓名", JsonValue.CreateStringValue("老劉"));            menb1.SetNamedValue("人品指數", JsonValue.CreateNumberValue(250));            menb1.SetNamedValue("是否磚家", JsonValue.CreateBooleanValue(true));            JsonObject menb2 = new JsonObject();            menb2.SetNamedValue("姓名", JsonValue.CreateStringValue("老趙"));            menb2.SetNamedValue("人品指數", JsonValue.CreateNumberValue(97));            menb2.SetNamedValue("是否磚家", JsonValue.CreateBooleanValue(false));            JsonArray arr1 = new JsonArray();            arr1.Add(menb1);            arr1.Add(menb2);            // 第一團隊資訊            JsonObject teamA = new JsonObject();            teamA.SetNamedValue("團隊名稱", JsonValue.CreateStringValue("牛B一隊"));            teamA.SetNamedValue("成員列表", arr1);            // ------------------------------------------------------------------------------            // 第二團隊的成員            JsonObject menbB1 = new JsonObject();            menbB1.SetNamedValue("姓名", JsonValue.CreateStringValue("小黃"));            menbB1.SetNamedValue("人品指數", JsonValue.CreateNumberValue(108));            menbB1.SetNamedValue("是否磚家", JsonValue.CreateBooleanValue(false));            JsonObject menbB2 = new JsonObject();            menbB2.SetNamedValue("姓名", JsonValue.CreateStringValue("小龍"));            menbB2.SetNamedValue("人品指數", JsonValue.CreateNumberValue(392));            menbB2.SetNamedValue("是否磚家", JsonValue.CreateBooleanValue(true));            JsonObject menbB3 = new JsonObject();            menbB3.SetNamedValue("姓名", JsonValue.CreateStringValue("老袁"));            menbB3.SetNamedValue("人品指數", JsonValue.CreateNumberValue(65));            menbB3.SetNamedValue("是否磚家", JsonValue.CreateBooleanValue(false));            JsonArray arr2 = new JsonArray();            arr2.Add(menbB1);            arr2.Add(menbB2);            arr2.Add(menbB3);            // 第二團隊資訊            JsonObject teamB = new JsonObject();            teamB.SetNamedValue("團隊名稱", JsonValue.CreateStringValue("牛B二隊"));            teamB.SetNamedValue("成員列表", arr2);            // 將兩個團隊的資訊放到一個數組中            JsonArray teams = new JsonArray();            teams.Add(teamA);            teams.Add(teamB);            // 將以上JSON對象轉換為字串            this.txtJson.Text = teams.Stringify();        }

上面代碼示範兩個牛B團隊的基本資料,而每個團隊中又包含各自的成員資訊。

結果就像所示:

 

是不是覺得這種產生JSON的方法有些複雜有點痛苦呢? 勿急,下一篇博文,我們將玩一些簡單的東東。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.